SQL 便捷求 集合操作: 合併,交集,差集,對稱差

-- create table if not EXISTS atmp(oid int8 PRIMARY key);
-- INSERT into atmp values(1) on conflict(oid) do update set OID = 1;
-- INSERT into atmp values(2) on conflict(oid) do update set OID = 2;
-- INSERT into atmp values(3) on conflict(oid) do update set OID = 3;
-- INSERT into atmp values(1) on conflict(oid) do update set OID = 1;
-- 
-- create table if not EXISTS atmp2(oid int8 PRIMARY key);
-- INSERT into atmp2 values(1) on conflict(oid) do update set OID = 1;
-- INSERT into atmp2 values(4) on conflict(oid) do update set OID = 4;
-- create table if not EXISTS atmpret(oid int8 PRIMARY key);
-- 
-- select  * from atmp natural join atmp2;
-- select  * from atmp as a inner join atmp2 as b  on a.oid = b.oid ;
-- select  * from atmp as a left join atmp2 as b  on a.oid = b.oid  ;
-- select  * from atmp as a full join atmp2 as b  on a.oid = b.oid ;
-- select  * from atmp as a right join atmp2 as b  on a.oid = b.oid ;
-- select  * from atmp as a  join atmp2 as b  on a.oid = b.oid ;

--求並
DELETE from atmpret;
insert into atmpret ( select  * from atmp UNION select  * from atmp2) on conflict(OID) do update set OID = (select  * from atmp UNION select  * from atmp2);
select * from atmpret;

--求交集
DELETE from atmpret;
insert into atmpret (select  * from atmp INTERSECT select  * from atmp2) on conflict(OID) do update set OID = (select  * from atmp INTERSECT select  * from atmp2);
select * from atmpret;
--求差 A- B
DELETE from atmpret;
insert into atmpret (select  * from atmp EXCEPT  select  * from atmp2) on conflict(OID) do update set OID = (select  * from atmp EXCEPT select  * from atmp2);
select * from atmpret;
--求對稱差
DELETE from atmpret;
insert into atmpret (((select  * from atmp EXCEPT select  * from atmp2))  UNION ((select  * from atmp2 EXCEPT select  * from atmp))) on conflict(OID) do update set OID = (((select  * from atmp EXCEPT select  * from atmp2))  UNION ((select  * from atmp2 EXCEPT select  * from atmp)));
select * from atmpret;

 

 

效率如何沒測試過, 有待測試, 但是應該比自己拼接方便快捷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章