原文: SQL语句中不同的连接JOIN
为了从两个表中获取数据,我们有时会用JOIN将两个表连接起来。通常有以下几种连接方式:
JOIN or INNER JOIN(内连接) : 这两个是相同的,要求两边表同时有对应的数据,返回行,任何一边缺失数据就不显示。
LEFT JOIN(左外连接):即使右边的表中没有匹配,也从左表返回所有的行。
RIGHT JOIN(右外连接):即使左边的表中没有匹配,也从右表返回所有的行。
FULL JOIN(全外连接):只要其中一个表中存在匹配就返回行。
如例,有grade表(课程号sn,分数scroe,学号id),student表(学号id,学生姓名name),要查询学生的姓名和成绩
当JOIN或是INNER JOIN时,SELECT s.name,g.sn,g.score from student as s join grade as g on s.id = g.id
或者
SELECT s.name,g.sn,g.score from student as s inner join grade as g on s.id = g.id
结果集如下
当LEFT JOIN时,
SELECT s.name,g.sn,g.score from student as s left join grade as g on s.id = g.id
当RIGHT JOIN时,
SELECT s.name,g.sn,g.score from student as s right join grade as g on s.id = g.id
当FULL JOIN时,
SELECT s.name,g.sn,g.score from student as s full join grade as g on s.id = g.id
注意,两个表连接时用on,在使用left join(right join或full join)时,on与where的区别是:
on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录
where条件是在临时表生成好后再对临时表进行过滤的条件,这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。如下图,
on条件为黄色部分
SELECT s.name,g.sn,g.score from student as s left join grade as g on s.id = g.id and score =90
SELECT s.name,g.sn,g.score from student as s left join grade as g on s.id = g.id where score =90