我有两张桌子,他们之间的关系是NO。 。
table1
---------------
NO. courses
---------------
1 CHEM 101
2 ENGL 101
3 MATH 101
4 PE 101
5 PHYS 101
6 IAS 101
table2
----------------------------
NO. ID Grades
----------------------------
1 5050 A+
2 5050 B
1 4040 A
2 4040 C
如何编写SQl查询,只为id为5050的输出表格table1和table2,输出应该是这样的
output
--------------------------
courses Grades
--------------------------
CHEM 101 A+
ENGL 101 B
MATH 101 null
PE 101 null
PHYS 101 null
IAS 101 null
答案 0 :(得分:1)
这是LEFT JOIN
的示例 - 保留第一个表中的所有行,但只保留第二个表中的匹配行。
在您的情况下,这看起来像:
select t1.*, t2.grade
from table1 t1 left join
table2 t2
on t1.no = t2.no and t2.id = 5050;