4

我有两张不同的桌子。一是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”的数据,结果将如下所示:

________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

有什么办法可以这样做吗?请任何人都可以帮助我。我以前从来没有这样做过。

先感谢您

4

2 回答 2

4

使用UNION ALL实际上只是UNION会做,因为学生没有头衔)。由于表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
于 2013-01-30T13:52:51.247 回答
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
于 2013-01-30T13:52:33.150 回答