** MySQL多表查询连接**
<1>交叉连接(笛卡尔积)
SELECT * FROM studentinfo,scoreinfo;
注意:了解交叉连接结果集生成过程。
studentinfo表
id name sex age birthday
1 张三 男 20 2018/5/15
2 李四 女 null null
3 王五 男 19 2019/5/21
scoreinfo表
id chinese math english
1 70 80 90
2 56 48 98
交叉连接
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
1 张三 男 20 2018/5/15 2 56 48 98
2 李四 女 1 70 80 90
2 李四 女 2 56 48 98
3 王五 男 19 2019/5/21 1 70 80 90
3 王五 男 19 2019/5/21 2 56 48 98
<2>内连接
SELECT * FROM studentinfo,scoreinfo WHERE studentinfo.id = scoreinfo.id;
#等价于
SELECT * FROM studentinfo INNER JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
SELECT name,chinese,math,english FROM studentinfo,scoreinfo WHERE studentinfo.id = scoreinfo.id;
内连接(根据where条件过滤掉不符合的记录)
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
1 张三 男 20 2018/5/15 2 56 48 98
2 李四 女 1 70 80 90
2 李四 女 2 56 48 98
3 王五 男 19 2019/5/21 1 70 80 90
3 王五 男 19 2019/5/21 2 56 48 98
最终结果集如下:
内连接
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
2 李四 女 2 56 48 98
<3>外连接
① 左外连接/左连接
SELECT * FROM studentinfo LEFT OUTER JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
#OUTER可以省略
SELECT * FROM studentinfo LEFT JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
左外连接
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
2 李四 女 2 56 48 98
3 王五 男 19 2019/5/21 NULL NULL NULL NULL
② 右外连接/右连接
SELECT * FROM studentinfo RIGHT OUTER JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
#OUTER可以省略
SELECT * FROM studentinfo RIGHT JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
右外连接
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
2 李四 女 2 56 48 98
NULL NULL NULL NULL NULL 4 85 25 68
③ 全外连接
MySQL不支持全外连接,所以只能采取关键字UNION来联合左、右连接的方法:
SELECT * FROM studentinfo LEFT JOIN scoreinfo ON studentinfo.id = scoreinfo.id
UNION
SELECT * FROM studentinfo RIGHT JOIN scoreinfo ON studentinfo.id = scoreinfo.id;
全外连接
id name sex age birthday id chinese math english
1 张三 男 20 2018/5/15 1 70 80 90
2 李四 女 2 56 48 98
3 王五 男 19 2019/5/21 NULL NULL NULL NULL
NULL NULL NULL NULL NULL 4 85 25 68