mysql 交集/差集/并集

表tsalsale

CREATE TABLE `tsalsale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `orgcode` varchar(255) DEFAULT NULL,
  `saleno` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1988 DEFAULT CHARSET=latin1

表xxzx

CREATE TABLE `xxzx` (
  `id` int(11) NOT NULL,
  `orgcode` varchar(255) DEFAULT NULL,
  `saleno` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1

这两张表中orgcode,saleno是有重复的,现在还要求两张表的差集,方法如下

方法1.使用left join方法,sql如下

select id,orgcode,saleno from tsalsale t left join 
(select id as i, orgcode as o, saleno as s from xxzx) as x

on t.orgcode=x.o and t.saleno=x.s where x.i is null;

方法2.使用union all方法(union取并集去重,union all不去重),sql如下

select count(1), orgcode,saleno from (
select distinct orgcode,saleno from tsalsale
union all
select distinct orgcode,saleno from xxzx

)t group by orgcode,saleno having count(1) = 1

至于取交集,则count(1)=2

取并集,直接union all即可

方法3使用exists,sql如下

select DISTINCT orgcode,saleno from tsalsale t where not exists (select distinct orgcode,saleno from xxzx where saleno = t.saleno)


猜你喜欢

转载自blog.csdn.net/jason_xiaojie_liu/article/details/80746683