SQL集合运算:差集、交集、并集
2011年03月30日 15:41:00
阅读数:15446
1、差集( except )
select a from t_a
except
select a from t_b
-- 也可写作:
select a from t_a where a not in (select a from t_b)
-- 多个字段时:
select a,b from t_a
except
select a,b from t_b
-- 多字段的查集也可写成:
select a,b from t_a where (a,b) not in (select a,b from t_b)
2、交集( intersect )
select a from t_a
intersect
select a from t_b
-- 也可写作:
select a from t_a where a in (select a from t_b)
3、并集( union )
select a from t_a
union distinct
select a from t_b
集合运算
这是一种二目运算,一共有四种四种运算符:并,差,交,笛卡尔积;
语法:
查询语句
[UNION | UNIONALL | INTERSECT | MINUS]
查询语句
UNION(并集)
Eg:SELECT *FROM dept
UNION
SELECT*FROM dept WHERE deptno = 10
注:查询 *** 作编写的过程中尽量使用UNION , UNION ALL代替 OR,提高查询速度
例:
查询工作是销售和clerk的;
SELECT*
FROM emp WHEREjob = ‘saleman’ or job = ‘clerk’
另一种方式:
SELECT * FROMemp WHERE job = ‘SALESMAN’
UNION
SELECT * FROMemp WHERE job = ‘CLERK’
UNION ALL(并集)
返回若干个查询结果,但是重复的也显示
Eg:SELECT * FROM dept
UNION ALL
SELECT*FROM dept WHERE deptno = 10
MINUS(差集)
返回若干个结果中不同的部分;
Eg:SELECT * FROM dept
MINUS
SELCT*FROM dept WHERE deptno = 10
INTERSECT(交集)
显示查询结果中相同的部分;
Eg:SELECT * FROM dept
INTERSECT
SELCT*FROM dept WHERE deptno = 10
————————————————
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)