目前有2个表:users和scores,它们的数据如下:
可见, id为1的xiaoming在scores中没有对应的记录,同样,user_id为5的score在users中没有对应的记录
mysql> SELECT * FROM users;
+----+----------+
| id | username |
+----+----------+
| 1 | xiaoming |
| 2 | awen |
| 3 | kate |
| 4 | lily |
+----+----------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM scores;
+---------+-------+
| user_id | score |
+---------+-------+
| 2 | 80 |
| 3 | 70 |
| 4 | 100 |
| 5 | 60 |
+---------+-------+
4 rows in set (0.00 sec)
1. 内连接, 从下可见2个表中在另一个表中没有对应记录的记录都没有出现
mysql> SELECT * FROM users INNER JOIN scores ON users.id = scores.user_id;
+----+----------+---------+-------+
| id | username | user_id | score |
+----+----------+---------+-------+
| 2 | awen | 2 | 80 |
| 3 | kate | 3 | 70 |
| 4 | lily | 4 | 100 |
+----+----------+---------+-------+
3 rows in set (0.00 sec)
2. 左连接, 从下可见JOIN左边的表中所有记录都有出现,id为1的没有对应的score记录的记录也有出现, 并且缺少的右表字段的数据全部补NULL
mysql> SELECT * FROM users LEFT JOIN scores ON users.id = scores.user_id;
+----+----------+---------+-------+
| id | username | user_id | score |
+----+----------+---------+-------+
| 1 | xiaoming | NULL | NULL |
| 2 | awen | 2 | 80 |
| 3 | kate | 3 | 70 |
| 4 | lily | 4 | 100 |
+----+----------+---------+-------+
4 rows in set (0.00 sec)
3. 右连接, 从下可见JOIN右边的表中所有记录都有出现,user_d为5的没有对应的user记录的记录也有出现, 并且缺少的左表字段的数据全部补NULL
mysql> SELECT * FROM users RIGHT JOIN scores ON users.id = scores.user_id;
+------+----------+---------+-------+
| id | username | user_id | score |
+------+----------+---------+-------+
| 2 | awen | 2 | 80 |
| 3 | kate | 3 | 70 |
| 4 | lily | 4 | 100 |
| NULL | NULL | 5 | 60 |
+------+----------+---------+-------+
4 rows in set (0.00 sec)
综上所述,
a. 内连接,显示两个表中有联系的的全部数据
b. 左连接, 显示左表的全部数据,右表中和左表没有联系的记录不出现
c. 右连接,显示右表的全部数据,左表中和右表没有联系的记录不出现