长时间没接触Mysql,连最基础的多表查询都忘了,汗…
先给出所有到的两个数据表
customers表
mysql> select * from customers;
+----+------------+-----------+------------------+
| id | first_name | last_name | email |
+----+------------+-----------+------------------+
| 1 | Boy | George | george@gmail.com |
| 2 | George | Michael | gm@gmail.com |
| 3 | David | Bowie | david@gmail.com |
| 4 | Blue | Steele | blue@gmail.com |
| 5 | Bette | Davis | bette@aol.com |
+----+------------+-----------+------------------+
orders表
mysql> select * from orders;
+----+------------+--------+-------------+
| id | order_date | amount | customer_id |
+----+------------+--------+-------------+
| 1 | 2016-02-10 | 99.99 | 1 |
| 2 | 2017-11-11 | 35.50 | 1 |
| 3 | 2014-12-12 | 800.67 | 2 |
| 4 | 2015-01-03 | 12.50 | 2 |
| 5 | 1999-04-11 | 450.25 | 5 |
+----+------------+--------+-------------+
1.Left Join
返回包括左表中的所有记录和右表中联结字段相等的记录
mysql> SELECT *
-> FROM customers LEFT JOIN orders
-> ON customers.id= orders.customer_id;
+----+------------+-----------+------------------+------+------------+--------+-------------+
| id | first_name | last_name | email | id | order_date | amount | customer_id |
+----+------------+-----------+------------------+------+------------+--------+-------------+
| 1 | Boy | George | george@gmail.com | 1 | 2016-02-10 | 99.99 | 1 |
| 1 | Boy | George | george@gmail.com | 2 | 2017-11-11 | 35.50 | 1 |
| 2 | George | Michael | gm@gmail.com | 3 | 2014-12-12 | 800.67 | 2 |
| 2 | George | Michael | gm@gmail.com | 4 | 2015-01-03 | 12.50 | 2 |
| 3 | David | Bowie | david@gmail.com | NULL | NULL | NULL | NULL |
| 4 | Blue | Steele | blue@gmail.com | NULL | NULL | NULL | NULL |
| 5 | Bette | Davis | bette@aol.com | 5 | 1999-04-11 | 450.25 | 5 |
+----+------------+-----------+------------------+------+------------+--------+-------------+
上面例子中左表是customers,所以会讲customers表中的所有字段都显示,其中David和Blue两个人并没有orders记录,但是也会显示null
2.Right Join
返回包括右表中的所有记录和左表中联结字段相等的记录
mysql> SELECT *
-> FROM customers RIGHT JOIN orders
-> ON customers.id= orders.customer_id;
+------+------------+-----------+------------------+----+------------+--------+-------------+
| id | first_name | last_name | email | id | order_date | amount | customer_id |
+------+------------+-----------+------------------+----+------------+--------+-------------+
| 1 | Boy | George | george@gmail.com | 1 | 2016-02-10 | 99.99 | 1 |
| 1 | Boy | George | george@gmail.com | 2 | 2017-11-11 | 35.50 | 1 |
| 2 | George | Michael | gm@gmail.com | 3 | 2014-12-12 | 800.67 | 2 |
| 2 | George | Michael | gm@gmail.com | 4 | 2015-01-03 | 12.50 | 2 |
| 5 | Bette | Davis | bette@aol.com | 5 | 1999-04-11 | 450.25 | 5 |
+------+------------+-----------+------------------+----+------------+--------+-------------+
3.Inner Join
返回符合条件判断的结果,搜索结果完全按照 ON 后面的语句来
最后附一张百科图:
图片来源https://www.cnblogs.com/logon/p/3748020.html