使用mysql在单个查询中从两个不同的表中选择

时间:2013-01-30 13:49:39

标签: php mysql sql

我有两张不同的牌桌。一个是instructor,第二个是student。两种表结构如下:

________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

现在,我想从两个表中选择数据,其中schoolid为'1',结果将类似于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

有没有办法这样做?请任何人帮助我。我以前从未这样做过。

先谢谢你

2 个答案:

答案 0 :(得分:4)

使用UNION ALL实际上只是UNION会做,因为学生没有头衔)。 SInce表STUDENT没有标题,您需要有一个带有别名title的空列,以便它与列数相匹配。如果您没有为标题添加额外的列,则会出现错误消息

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

完整查询,

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

答案 1 :(得分:2)

UNION是关键:

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