在MySQL中,我們可以利用交集、并集、差集等命令來實現對多個數據集的相交、合并、差分等操作。
下面分別介紹這三種命令的用法:
交集命令:intersect
intersect,即求多個數據集的交集。用法如下:
SELECT column_name(s) FROM table1 INTERSECT SELECT column_name(s) FROM table2;
示例:
SELECT * FROM table1 WHERE column_name IN (SELECT column_name FROM table2);
并集命令:union
union,即求多個數據集的并集。用法如下:
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
示例:
SELECT * FROM table1 WHERE column_name NOT IN (SELECT column_name FROM table2) UNION ALL SELECT * FROM table2;
差集命令:except
except,即求多個數據集的差集。用法如下:
SELECT column_name(s) FROM table1 EXCEPT SELECT column_name(s) FROM table2;
示例:
SELECT * FROM table1 WHERE column_name NOT IN (SELECT column_name FROM table2);