我有两个不同的表。一个是 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
有什么办法可以做到这一点吗?请任何人帮助我。我以前从未这样做过。
提前致谢
最佳答案
使用 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
关于php - 使用mysql从单个查询中的两个不同表中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14605632/