目前有2個表:users表和scores表,它們的數據如下:
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)
可見, id爲1的xiaoming在scores中沒有對應的記錄,同樣,user_id爲5的score在users中沒有對應的記錄。
1、內連接, 從下面的SQL查詢可見,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、左連接, 從下面的SQL查詢可見,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、右連接, 從下面的SQL查詢可見,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. 右連接,顯示右表的全部數據,左表中和右表沒有聯繫的記錄不出現。