不同数据库取并集、交集、差集


一.并集:

需求:汇总t1、t2两表的数据

mysql、postgresql、oracle数据库取并集都是用union/union all关键字,不再赘述

二.交集:

需求:选出既在t1表又在t2表的数据

1.mysql数据库取交集,没有对应的关键字,只能把所有要查询的字段都加到where条件上,如下

select t1.name, t1.age from t1, t2 where t1.name = t2.name and t1.age = t2.age   //如果t1, t2不是表而只是结果集的话,只需要加上with t1 as(...), t2 as (...)就可以了

2.postgresql/oracle数据库取交集,可以用intersect关键字,如下

select t1.name, t1.age from t1

intersect

select t2.name, t2.age from t2

三.差集:

需求:选出在t1表中但不在t2表中的数据

1.mysql数据库取差集,也没有对应的关键字,有2种方式:

①.用not in

select name, age from t1

where (t1.name, t1.age) not in (select name, age from t2)

注意,where后面字段如果有多个,必须用括号括起来,同时子查询语句也必须用括号括起来

not in这种方式虽然写法简单,但是如果两个表的数据很多的话,那查询起来非常慢

②.用连表查询

sql92:

select t1.name, t1.age from t1

where t1.name != t2.name or t1.age != t2.age

或是

sql99:

select t1.name, t1.age inner join t2

on t1.name != t2.name or t1.age != t2.age

当然,如果t1、t2有多个字段的话,就要一个一个比对,然后用or连接起来

必须用内连接,这点想想左连接和右连接查出的结果集就明白了。

2.postgresql取差集,可以用except关键字,如下:

select t1.name, t1.age from t1

except

select t2.name, t2.age from t2

3.oracle数据库取差集,可以用minus关键字,如下

select t1.name, t1.age from t1

minus

select t2.name, t2.age from t2

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM