php - 使用mysql从单个查询中的两个不同表中进行选择

标签 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”的数据,结果如下所示:

________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/

相关文章:

php - 当我们知道sql中的大海捞针时,就需要寻找针

ODBC 中的 SQL 语句

php - Cron 作业不起作用,Laravel 和 cPanel

php - 无需编写 PHP 代码即可显示许多 sql 查询的结果?

php - SQL,如果PHP值为空则忽略原因

sql - MYSQL REGEXP/RLIKE 有什么建议吗?

在 Stack Overflow 数据转储上运行查询时,SQL Server 非常慢

php - 使用匿名绑定(bind)时如何在 LDAP 中搜索用户?

MySQL查询问题: Can't select columns from another table

MySQL 选择 rand 并排除有条件的用户