測試數據:
test01
test02
一、並集
使用UNION ALL關鍵字
UNION ALL (並集 不去重)
select * from test01 UNION ALL select * from test02
結果如下,六條數據全部累積起來了,並且有重復的。
UNION (並集 去重)
select * from test01 UNION select * from test02
結果如下,可以跟上面的對比少了兩條,王浩與王浩3
二、交集
-- INNER JOIN (等值連接) 只返回兩個表中聯結字段相等的行 -- inner join並不以誰為基礎,它只顯示符合條件的記錄. SELECT a.* FROM test01 a INNER JOIN test02 b ON a.id=b.id AND a.name=b.name; -- USING(id,name) 等價於 on后面的條件 SELECT a.* FROM test01 a INNER JOIN test02 b USING(id,name)
三、差集
-- 差集 SELECT a.* FROM test01 a LEFT JOIN test02 b ON a.id=b.id AND a.name=b.name WHERE b.id IS NULL
參考文章:
https://blog.csdn.net/sanzhongguren/article/details/76615464