内连接
- 等值连接
依据两个表中相同内容的字段进行连接
SELECT s.name, g.* FROM student s JOIN grade g ON s.
id= g.
id;
-
非等值连接
依据两个表中内容相关列(非相同)字段进行连接
SELECT g.id, g.yuwen, s.level FROM grade g JOIN score_level s ON g.yuwen BETWEEN s.low AND s.high;
自连接
外连接
-
左连接
保留左表所有数据和共有数据,若右表没有对应值,默认置null
SELECT s.id, s.name, g.yuwen FROM student s LEFT JOIN grade g ON s.id = g.id;
-
右连接
保留右表所有数据和共有数据,若左表没有对应值,默认置null
SELECT s.id, s.name, g.yuwen FROM student s RIGHT JOIN grade g ON s.id = g.id;
多表连接
语句顺序
select
...
from
a
join
b
on
...
join
c
on
...
where
...
例:
SELECT s.name, s.id, g.yuwen, sl.level FROM grade g JOIN student s ON s.id = g.id JOIN score_level sl ON g.yuwen BETWEEN sl.low AND sl.high where g.yuwen > 70;
注意:
- 上面表示a表和b连接,然后a表再和c连接,其结果合并在一起。不是a表先连接b,其结果再和c连接
- where语句放在最后