欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL 查询结果取交集的实现方法

程序员文章站 2023-12-20 22:11:22
1 mysql中如何实现以下sql查询 (select s.name from student s, transcript t where s.studid = t.stu...
1
mysql中如何实现以下sql查询
(select s.name
from student s, transcript t
where s.studid = t.studid and t.crscode = 'cs305')
intersect
(select s.name
from student s, transcript t
where s.studid = t.studid and t.crscode = 'cs315')
请各位不吝赐教,小弟先谢过~
解:
取交集
select a.* from
(
select s.name
from student s, transcript t
where s.studid = t.studid and t.crscode = 'cs305'
) as a
cross join
(
select s.name
from student s, transcript t
where s.studid = t.studid and t.crscode = 'cs315'
) as b on a.name = b.name;

2.
select * from (
select distinct col1 from t1 where...
union all
select distinct col1 from t1 where...
) as tbl
group by tbl.col1 having count(*) = 2

3.
交集:
select * from table1 as a join table2 as b on a.name =b.name
举例:
表a:
fielda
001
002
003
表b:
fielda
001
002
003
004
请教如何才能得出以下结果集,即表a, b行交集
fielda
001
002
003
答案:select a.fielda from a inner join b on a.fielda=b.fielda
差集:
not in 表示差集
select * from table1 where name not in (select name from table2)

上一篇:

下一篇: