李壮飞的回答:使用 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) Color的回答:求交集的关键字是 intersect ,例: select * from emp where deptno in (10,20) intersect select * from emp where deptno in (20,30); 刘梦露的回答:select a.*,b.* from table1 as a left join table2 as b on a.id=b.id 以左侧表为基准,也可以使用right以右侧表为基准 陈子和的回答:(子查询)union(子查询) (子查询)and(子查询) 晨钰的回答:select xxx.a1,yyy.b1 from xxx, yyy where xxx.a2=yyy.b2 |