我有两个表:USER和SUBJECTS
USER表
SUBJECT表
表USER中的SUBJECT1,SUBJECT2,SUBJECT3是表SUBJECT中列ID的外键。
我尝试编写一个SQL查询,该查询返回第一个表中的所有列以及外键引用的值,以显示一个用户(教师)可以一次教授三个主题。我希望在结果中获取第二个表中的值,如下所示:
| ID | NAME | AGE | ADDRESS | SUBJECT1 | SUBJECT2 | SUBJECT3 |
+----+-------+-----+---------+----------+----------+----------+
| 1 | John | 30 | London | Math | English | Sports |
| 2 | Marry | 40 | London | English | Sports | Biology |
| 3 | Tom | 35 | Paris | English | Sports | Russian |
答案 0 :(得分:2)
尝试以下内容;)
select
u.ID, u.NAME, u.AGE, u.ADDRESS, s1.NAME as SUBJECT1, s2.NAME as SUBJECT2, s3.NAME as SUBJECT3
from USER u
left join SUBJECT s1 on u.SUBJECT1 = s1.ID
left join SUBJECT s2 on u.SUBJECT2 = s2.ID
left join SUBJECT s3 on u.SUBJECT3 = s3.ID