创建两个表
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