MySQL内连接、左外连接、右外连接、全外连接

连接的优势是减少了外键的使用。
内连接:最常见的等值连接,指连接结果仅包含符合连接条件的行,参与连接的两个表都应该符合连接条件。
inner join或join on condition

//首先创建两个表person和card,内容如下
 select * from card;
+------+----------+
| id   | cardName |
+------+----------+
|    1 | cardyi   |
|    2 | carder   |
|    3 | cardsan  |
|    4 | cardsi   |
|    5 | cardwu   |
|    6 | cardliu  |
+------+----------+
 select * from person;
+------+------+--------+
| id   | name | cardId |
+------+------+--------+
|    1 | pyi  |      1 |
|    1 | pyi  |      2 |
|    1 | pyi  |      4 |
|    1 | pyi  |      7 |
|    2 | per  |      6 |
+------+------+--------+

内连接示意:

 select * from person inner join card on person.cardId=card.id;//需要两个表都满足连接条件。
+------+------+--------+------+----------+
| id   | name | cardId | id   | cardName |
+------+------+--------+------+----------+
|    1 | pyi  |      1 |    1 | cardyi   |
|    1 | pyi  |      2 |    2 | carder   |
|    1 | pyi  |      4 |    4 | cardsi   |
|    2 | per  |      6 |    6 | cardliu  |
+------+------+--------+------+----------+

外连接:包含左外连接、右外连接和全外连接
左外连接:left join on或者left outer join on

select * from person left join card on person.cardId =card.id;
+------+------+--------+------+----------+
| id   | name | cardId | id   | cardName |
+------+------+--------+------+----------+
|    1 | pyi  |      1 |    1 | cardyi   |
|    1 | pyi  |      2 |    2 | carder   |
|    1 | pyi  |      4 |    4 | cardsi   |
|    2 | per  |      6 |    6 | cardliu  |
|    1 | pyi  |      7 | NULL | NULL     |
+------+------+--------+------+----------+

左边的全显示,右边有相等就显示,没有就显示null
右外连接:right join或者right outer join

select * from person right join card on person.cardId=card.id;
+------+------+--------+------+----------+
| id   | name | cardId | id   | cardName |
+------+------+--------+------+----------+
|    1 | pyi  |      1 |    1 | cardyi   |
|    1 | pyi  |      2 |    2 | carder   |
|    1 | pyi  |      4 |    4 | cardsi   |
|    2 | per  |      6 |    6 | cardliu  |
| NULL | NULL |   NULL |    3 | cardsan  |
| NULL | NULL |   NULL |    5 | cardwu   |
+------+------+--------+------+----------+

右边有的全显示,左边有的显示,左边没有的显示null。左边有,右边没有的不显示。
全外连接:full join
mysql本身不支持full join
如果要实现full join,就把左连接的实现和右连接的实现进行union

select * from person left join card on person.cardId=card.id
union
select * from person right join card on person.cardId=card.id;
+------+------+--------+------+----------+
| id   | name | cardId | id   | cardName |
+------+------+--------+------+----------+
|    1 | pyi  |      1 |    1 | cardyi   |
|    1 | pyi  |      2 |    2 | carder   |
|    1 | pyi  |      4 |    4 | cardsi   |
|    2 | per  |      6 |    6 | cardliu  |
|    1 | pyi  |      7 | NULL | NULL     |
| NULL | NULL |   NULL |    3 | cardsan  |
| NULL | NULL |   NULL |    5 | cardwu   |
+------+------+--------+--。----+----------+

左边的全显示,右边的全显示,左边有,右边没有,右边为null;右边有,左边没有,左边为null

原创文章 64 获赞 27 访问量 9416

猜你喜欢

转载自blog.csdn.net/weixin_44893585/article/details/104652002