1. 程式人生 > >MySQL 並集、交集、差集

MySQL 並集、交集、差集

建立兩個表

CREATE TABLE `object_a` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `oname` varchar(50) DEFAULT NULL,
  `odesc` varchar(50) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
新增資料

CREATE TABLE `object_b` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `oname` varchar(50) DEFAULT NULL,
  `odesc` varchar(50) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
新增資料

查詢並集(union all)

SELECT oname,odesc FROM object_a
UNION ALL
SELECT oname,odesc FROM object_b

結果如下


查詢並集(union)

SELECT oname,odesc FROM object_a
UNION
SELECT oname,odesc FROM object_b

結果如下



PS:union自帶去重

查詢交集

SELECT a.oname,a.odesc FROM object_a a INNER JOIN object_b b ON a.oname=b.oname AND a.odesc=b.odesc

等價於

SELECT a.oname,a.odesc FROM object_a a INNER JOIN object_b b USING(oname,odesc)

結果如下



PS:別的資料庫可以試試這種寫法

SELECT oname,odesc FROM object_a 
INTERSECT
SELECT oname,odesc FROM object_b 
查詢差集
SELECT a.oname, a.odesc 
FROM
  object_a a 
  LEFT JOIN object_b b 
    ON a.oname = b.oname 
    AND a.odesc = b.odesc 
WHERE b.id IS NULL 

結果如下


PS:別的資料庫可以試試這種寫法

SELECT a.oname, a.odesc FROM object_a a 
MINUS 
SELECT b.oname, b.odesc FROM object_b b