Hardik
Hardik

Reputation: 1411

select from two different tables in single query using mysql

I have two different tables. One is instructor and second is student. Both table structure are as follows:

________INSTRUCTOR_________

instructorid schoolid instructorusername instructorfirstname instructorlastname instructortitle level
1             1        inst_A              first_A             Last_A              RN            3
2             1        inst_B              first_B             Last_B              TD            3
3             1        inst_C              first_C             Last_C              FP            3

________STUDENT_________

studentid   schoolid  studentusername    studentfirstname    studentlastname    level
1             1        stud_A              first_A             Last_A            4
2             1        stud_B              first_B             Last_B            4
3             1        stud_C              first_C             Last_C            4

Now, I want to select data from both tables where schoolid is '1' and the result will be like Bellow :

________RESULT_________

id schoolid username firstname lastname title level
1   1        inst_A   first_A   Last_A   RN    3
2   1        inst_B   first_B   Last_B   TD    3
3   1        inst_C   first_C   Last_C   FP    3
1   1        stud_A   first_A   Last_A         4
2   1        stud_B   first_B   Last_B         4
3   1        stud_C   first_C   Last_C         4

Is there any way to do like this? Please can any one help me for this. I have never done like this before.

Thank you in Advance

Upvotes: 4

Views: 5931

Answers (2)

John Woo
John Woo

Reputation: 263893

use UNION ALL (actually just UNION will do since students have no title). SInce table STUDENT doesn't have title, you need to have an empty column with alias title so it will match the column count. If you don't add extra column for title, you will have error message

The used SELECT statements have a different number of columns...

Full Query,

SELECT  schoolid, 
        instructorusername username, 
        instructorfirstname firstName, 
        instructorlastname lastName,
        instructortitle title,
        level
FROM    instructors
UNION 
SELECT  schoolid, 
        studentusername username, 
        studentfirstname firstName, 
        studentlastname lastName,
        '' title,
        level
FROM    students

Upvotes: 4

Kris
Kris

Reputation: 14468

UNION is the key here:

select schoolid, instructorusername as username,  instructorfirstname as firstname, instructorlastname as lastname, instructortitle as title
from INSTRUCTOR
UNION
select schoolid, studentusername as username,  studentfirstname as firstname, studentlastname as lastname, "" as title
from STUDENT

Upvotes: 2

Related Questions