基于SQL求集合的交、并、补

对数据库查询结果集求补(差)、交、并集,可利用SQL的EXCEPT(补集)、INTERSECT(交集)和UNION(并集)关键词,其中Mysql仅支持UNION,但可以利用SQL实现EXCEPT、INTERSECT的功能。

作者接下来将给出实验用表以及具体的SQL脚本语句。


实验用表

为进行实验,作者在SQL Server数据库下共建立了t1、t2两张表,两张表除主键id外均有个两字段stu_id和teacher_id。

t1表

id stu_id teacher_id
1 S0001 T01
2 S0002 T01
3 S0003 T02
4 S0004 T02
5 S0005 T03
6 S0002 T04

t2表

id stu_id teacher_id
1 S0002 T05
2 S0003 T03
3 S0006 T02
4 S0007 T04
5 S0005 T03

SQL脚本语句

/*求补(差)集demo1,一个字段*/
SELECT a.stu_id FROM t1 a
EXCEPT
SELECT a.stu_id FROM t2 a;
/*和上面等效,可用于Mysql*/
SELECT a.stu_id FROM t1 a
WHERE a.stu_id NOT IN
(SELECT a.stu_id FROM t2 a);

/*求补(差)集demo2,多个字段求差集*/
SELECT a.stu_id,a.teacher_id FROM t1 a
WHERE a.stu_id NOT IN
(SELECT a.stu_id FROM t2 a)
AND a.teacher_id NOT IN
(SELECT a.teacher_id FROM t2 a);

/*求交集demo1,多个字段求交集*/
SELECT a.stu_id,a.teacher_id FROM t1 a
INTERSECT
SELECT a.stu_id,a.teacher_id FROM t2 a;
/*和上面等效,可用于Mysql*/
SELECT a.stu_id,a.teacher_id FROM t1 a
WHERE a.stu_id+a.teacher_id IN
(SELECT a.stu_id+a.teacher_id FROM t2 a);

/*求交集demo2*/
/*下面语句把交集中重复出现的去掉*/
SELECT a.stu_id FROM t1 a
INTERSECT
SELECT a.stu_id FROM t2 a;

/*下面三个语句不会把重复的去掉,可使用DISTINCT去重*/
SELECT a.stu_id FROM t1 a
WHERE a.stu_id IN
(SELECT a.stu_id FROM t2 a);

SELECT a.stu_id FROM t1 a,t2 b
WHERE a.stu_id=b.stu_id;

SELECT a.stu_id FROM t1 a
WHERE EXISTS
(SELECT * FROM t2 b WHERE a.stu_id=b.stu_id);

/*求并集demo*/
/*不会去重*/
SELECT a.stu_id FROM t1 a
UNION ALL
SELECT a.stu_id FROM t2 a;
/*去重,Mysql中可以在UNION后加DISTINCT*/
SELECT a.stu_id FROM t1 a
UNION
SELECT a.stu_id FROM t2 a;

你可能感兴趣的:(SQL)