使用set操作sql查找常见元素

问题描述

检索完成过绘画和素描的艺术家的ID,名字和姓氏

我尝试使用以下方式联接表

SELECT artist.artist_id,artist.last_name,artist.first_name FROM artist
INTERSECT
SELECT artwork.artist_id 
from artwork
where  technique ='drawing' and technique= 'painting' 

但是,表中的列数必须相同。

image

解决方法

一个选项使用聚合:

select a.*
from artist a
inner join artwork aw on aw.artist_id = a.artist_id
where aw.technique in ('painting','drawing')
group by a.artist_id
having count(distinct aw.technique) = 2

您也可以使用exists

select a.*
from artist a
where exists (select 1 from artwork aw where aw.artist_id = a.artist_id and aw.technique = 'painting')
  and exists (select 1 from artwork aw where aw.artist_id = a.artist_id and aw.technique = 'drawing')
,

可以使用intersect,但这在artwork表上。因此,以下内容返回了既有绘画又有绘画的艺术家:

select aw.artist_id 
from artwork aw
where aw.technique = 'drawing' 
intersect
select aw.artist_id 
from artwork aw
where aw.technique = 'painting' ;

要获取艺术家信息,可以使用joinexistsin

select a.*
from artist a
where a.artist_id in (select aw.artist_id 
                      from artwork aw
                      where aw.technique = 'drawing' 
                      intersect
                      select aw.artist_id 
                      from artwork aw
                      where aw.technique = 'painting'
                     );

还有其他方法,例如条件聚合。我倾向于使用:

select a.*
from artist a join
     artwork aw
     using (artist_id)
where aw.technique in ('drawing','painting')
group by a.artist_id   -- presumably this is a primary key
having count(distinct aw.technique) = 2;

或者GMB建议的exists方法。