2

Join

  • 本文的集合图片来源参考3

数据集

image

1. LEFT JOIN

  • 在两张表进行连接查询时,会返回左表所有的行,即使在右表中没有匹配的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
LEFT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id

image

  • 在两张表进行连接查询时,会返回左表独有的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
LEFT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id
WHERE t2.group_id IS NULL

image

2. INNER JOIN

  • 在两张表进行连接查询时,只保留两张表中完全匹配的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
INNER JOIN tb_test_b t2 
ON t1.group_id = t2.group_id

image

3. RIGHT JOIN

  • 在两张表进行连接查询时,会返回右表所有的行,即使在左表中没有匹配的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
RIGHT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id

image

  • 在两张表进行连接查询时,会返回右表独有的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
RIGHT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id

image

4. FULL JOIN

  • 在两张表进行连接查询时,返回左表和右表,以及两个表中没有匹配的结果集
  • ==Mysql中不支持FULL JOIN,但可以用UNION代替==

image

SELECT t1.*,t2.*
FROM tb_test_a t1
LEFT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id
UNION
SELECT t1.*,t2.*
FROM tb_test_a t1
RIGHT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id

image

  • 在两张表进行连接查询时,会返回左边独有和右边独有的结果集

image

SELECT t1.*,t2.*
FROM tb_test_a t1
LEFT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id
WHERE t2.group_id IS NULL
UNION
SELECT t1.*,t2.*
FROM tb_test_a t1
RIGHT JOIN tb_test_b t2 
ON t1.group_id = t2.group_id
WHERE t1.group_id IS NULL

image

注意

1、结果集的数据顺序,不一定是之前的数据顺序,

参考

  1. https://blog.csdn.net/rongbo_...
  2. https://www.cnblogs.com/zhoug...
  3. https://segmentfault.com/a/11...

Tom_Chou
6 声望0 粉丝