INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
创建两个表
SELECT * FROM tb1;
id |
title |
author |
date |
1 |
学习java |
csdn |
2017-06-10 |
2 |
学习c |
csdn |
2017-04-12 |
3 |
学习c# |
github |
2017-04-12 |
4 |
学习c++ |
github |
2017-04-12 |
5 |
学习python |
FK |
2017-04-12 |
SELECT * FROM tb2;
author |
count |
github |
10 |
csdn |
20 |
blog |
22 |
INNER JOIN(也可以省略 INNER 使用 JOIN,效果一样)
SELECT a.id, a.author, b.count FROM tb1 a INNER JOIN tb2 b ON a.author = b.author;
等价于:
SELECT a.id, a.author, b.count FROM tb1 a, tb2 b WHERE a.author = b.author;
a.id |
a.author |
b.count |
1 |
csdn |
20 |
2 |
csdn |
20 |
3 |
github |
10 |
4 |
github |
10 |
LEFT JOIN
SELECT a.id, a.author, b.count FROM tb1 a LEFT JOIN tb2 b ON a.author = b.author;
id |
author |
count |
1 |
csdn |
20 |
2 |
csdn |
20 |
3 |
github |
10 |
4 |
github |
10 |
5 |
FK |
NULL |
RIGHT JOIN
SELECT a.id, a.author, b.count FROM tbl a RIGHT JOIN tb2 b ON a.author = b.author;
id |
author |
count |
1 |
csdn |
20 |
2 |
csdn |
20 |
3 |
github |
10 |
4 |
github |
10 |
NULL |
NULL |
22 |