----+
| 1 | aaa | 1 |
| 2 | bbb | 2 |
| 3 | bbb | 4 |
+----+------+-------+
mysql> select * from tb;
+----+------+
| id | name |
+----+------+
| 1 | xxx |
| 2 | yyy |
| 3 | yyy |
+----+------+
?
?
1.笛卡尔积查询:两张表中一条一条对应的记录,m条记录和n条记录查询,最后得到m*n条记录,其中很多错误数据
select * from ta ,tb;
mysql> select * from ta ,tb;
+----+------+-------+----+------+
| id | name | tb_id | id | name |
+----+------+-------+----+------+
| 1 | aaa | 1 | 1 | xxx |
| 2 | bbb | 2 | 1 | xxx |
| 3 | bbb | 4 | 1 | xxx |
| 1 | aaa | 1 | 2 | yyy |
| 2 | bbb | 2 | 2 | yyy |
| 3 | bbb | 4 | 2 | yyy |
| 1 | aaa | 1 | 3 | yyy |
| 2 | bbb | 2 | 3 | yyy |
| 3 | bbb | 4 | 3 | yyy |
+----+------+-------+----+------+
?
?
2.内连接:查询两张表中都有的关联数据,相当于利用条件从笛卡尔积结果中筛选出了正确的结果。
select * from ta ,tb where ta.tb_id = tb.id;
select * from ta inner join tb on ta.tb_id = tb.id;
mysql> select * from ta inner join tb on ta.tb_id = tb.id;
+----+------+-------+----+------+
| id | name | tb_id | id | name |
+----+------+-------+----+------+
| 1 | aaa | 1 | 1 | xxx |
| 2 | bbb | 2 | 2 | yyy |
+----+------+-------+----+------+
?
?
3.外连接
?
(1)左外连接:在内连接的基础上增加左边有右边没有的结果
select * from ta left join tb on ta.tb_id = tb.id;
mysql> select * from ta left join tb on ta.tb_id = tb.id;
+----+------+-------+------+------+
| id | name | tb_id | id| name |
+----+------+-------+------+------+
| 1 | aaa | 1 | 1 | xxx |
| 2 | bbb | 2 | 2 | yyy |
| 3 | bbb | 4 | NULL | NULL |
+----+------+-------+------+------+
?
?
(2)右外连接:在内连接的基础上增加右边有左边没有的结果
select * from ta right join tb on ta.tb_id = tb.id;
mysql> select * from ta right join tb on ta.tb_id = tb.id;
+------+------+-------+----+------+
| id| name | tb_id | id | name |
+------+------+-------+----+------+
| 1 | aaa | 1 | 1 | xxx |
| 2 | bbb | 2 | 2 | yyy |
| NULL | NULL | NULL | 3 | yyy |
+------+------+-------+----+------+
?
?
(3)全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
select * from ta full join tb on ta.tb_id = tb.id; --mysql不支持全外连接
select * from ta left join tb on ta.tb_id = tb.id
union
select * from ta right join tb on ta.tb_id = tb.id;
mysql> select * from ta left join tb on ta.tb_id = tb.id
-> union
-> select * from ta right join tb on ta.tb_id = tb.id; --mysql可以使用此种方式间接实现全外连接
+------+------+-------+------+------+
| id| name | tb_id | id| name |
+------+------+-------+------+------+
| 1 | aaa | 1 | 1 | xxx |
| 2 | bbb | 2 | 2 | yyy |
| 3 | bbb | 4 | NULL | NULL |
| NULL | NULL | NULL | 3 | yyy |
+------+------+-------+------+------+
?