下面简答介绍下MySQL中常用的JOIN操作,以及会犯得一些简单错误
tips:图是引用网络,如果错误,请指出,感谢。
在MySQL中,逗号(','), JOIN, CROSS JOIN, INNER JOIN在语法上是等价的,能够互相替换(在标准SQL中,它们是不等价的)
然而,逗号(',')运算的优先级小于JOIN, CROSS JOIN, INNER JOIN, LEFT JOIN等,
如果混合使用,则会造on列子句中出现"Unknown column 'col_name' "错误
例如:
SELECT * FROM t1, t2 JOIN t3 ON (t1.i1 = t3.i3);
ERROR 1054 (42S22): Unknown column 't1.i1' in 'on clause'
因为该语句被解析成了:
SELECT * FROM t1, (t2 join t3 on (t1.i1 = t3.i3));
表达式在on和where后的区别
如:
on A.ID = B.ID and B.ID<3:
先筛选出B表ID小于3的结果,在进行JOIN操作
on A.ID = B.ID where B.ID<3:
先进行JOIN操作,在对结果集筛选出B.ID小于3的结果
在inner join中,两者结果没有区别:
如:
select A.ID as AID, B.ID as BID from A join B on A.ID = B.ID and B.ID<3;
select A.ID as AID, B.ID as BID from A join B on A.ID = B.ID where B.ID<3;
输出结果:
+-----+-----+
| AID | BID |
+-----+-----+
| 1 | 1 |
| 2 | 2 |
+-----+-----+
2 rows in set (0.00 sec)
在left join中,两者结果有区别:
select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID and B.ID<3;
输出结果:
+-----+------+
| AID | BID |
+-----+------+
| 1 | 1 |
| 2 | 2 |
| 3 | NULL |
| 4 | NULL |
| 5 | NULL |
| 6 | NULL |
+-----+------+
select A.ID as AID, B.ID as BID from A left join B on A.ID = B.ID where B.ID<3 ;
输出结果:
+-----+------+
| AID | BID |
+-----+------+
| 1 | 1 |
| 2 | 2 |
+-----+------+
JOIN图示:
inner join(内连接):
将A表和B表中存在连接关系的字段,组成的结果集(A表和B表的交集)
关系表示如图:
例句:
select * from a inner join b on a.id=b.id;
===========================
left join(左连接,属于外连接):
以左表为准,去右表找数据,如果没有匹配的数据,则以null补位右表的数据,所以输出结果数为左表原数据集(right join同理)
关系表示如图:
例句:
select * from a left join b on a.id=b.id;
查找A表中有而且B表中没有的集合,表示为图:
语句为:
select * from a left join b on a.id=b.id where b.id is null;
查找A表中有而且B表中也有的集合,表示为图:
因此left join可以转换为 inner join
语句为:
select * from a left join b on a.id=b.id where b.id is not null;