交集sql
㈠ sql如何查询两个表的交集
首先俩个表要存在关联关系,例:表A中的ID列和表B中的ID列是一样的数据,且唯一
则:
select * from A
left jion B on A.ID=B.ID
㈡ 求多个表交集的SQL语句是什么呀
使用 EXISTS 和 NOT EXISTS 查找交集与差集
使用 EXISTS 和 NOT EXISTS 引入的子查询可用于两种集合原理的操作:交集与差集。两个集合的交集包含同时属于两个原集合的所有元素。差集包含只属于两个集合中的第一个集合的元素。
city 列中 authors 和 publishers 的交集是作者和出版商共同居住的城市的集合。
USE pubs
SELECT DISTINCT city
FROM authors
WHERE EXISTS
(SELECT *
FROM publishers
WHERE authors.city = publishers.city)
下面是结果集:
city
--------
Berkeley
(1 row(s) affected)
当然,该查询可以写成一个简单的联接。
USE pubs
SELECT DISTINCT authors.city
FROM authors INNER JOIN publishers
ON authors.city = publishers.city
city 列中 authors 和 publishers 的差集是作者所居住的、但没有出版商居住的所有城市的集合,也就是除 Berkeley 以外的所有城市。
USE pubs
SELECT DISTINCT city
FROM authors
WHERE NOT EXISTS
(SELECT *
FROM publishers
WHERE authors.city = publishers.city)
该查询也可以写成:
USE pubs
SELECT DISTINCT city
FROM authors
WHERE city NOT IN
(SELECT city
FROM publishers)
㈢ SQL集合运算:差集、交集、并集
原
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
㈣ 如何使用SQL语句求出交集
求交集嫌漏团的关键搜没字是 intersect ,例芹橘:
select * from emp where deptno in (10,20)
intersect
select * from emp where deptno in (20,30);