友情提示:本文数据表皆来自菜鸟教程,如有侵犯,请联系笔者进行修改。
先讲解left join:
假设有A表和B表,分别对应左右表,left和right。
A表:website表
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 天猫 | https://www.tianmao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 百度 | http://baidu.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
B表:log表
+-----+---------+-------+------------+
| aid | site_id | count | date |
+-----+---------+-------+------------+
| 1 | 1 | 45 | 2020-05-10 |
| 2 | 3 | 100 | 2020-05-13 |
| 3 | 1 | 230 | 2020-05-14 |
| 4 | 2 | 10 | 2020-05-14 |
| 5 | 5 | 205 | 2020-05-14 |
| 6 | 4 | 13 | 2020-05-15 |
| 7 | 3 | 220 | 2020-05-15 |
| 8 | 5 | 545 | 2020-05-16 |
| 9 | 3 | 201 | 2020-05-17 |
+-----+---------+-------+------------+
9 rows in set (0.00 sec)
使用left join来访问所有网站以及它们的访问量:
SELECT website.name, log.count, log.date
FROM website
LEFT JOIN log
ON website.id=log.site_id
ORDER BY log.count DESC;
现在讲解right join:
A表还是左边的website,B表还是右边的log。
使用right join来访问所有访问量对应的网站:
SELECT website.name,log.count,log.date
FROM website
RIGHT JOIN log
ON log.site_id=website.id
ORDER BY log.count DESC;
总结:
left就是多表查询中只要左边的数据,
right就是多表查询中只要右边的数据。