这是我的问题:
我有一个由两列组成的表idtypedata
:
IDdata
IDtype
它们都不是唯一的。
我想输出一个显示IDdata
的表格,以便每次在IDtype
找到给定列表的所有匹配IDdata
时显示{。}}。
举个例子:
列表(12,5)
IDdata IDtype
221 12
221 5
157 12
187 5
只有当IDdata
符合所有列表参数时,查询才会返回IDtype
:
IDdata
221
答案 0 :(得分:3)
这也称为关系分裂:
select iddata
from idtypedata
where idtype in (12,5)
group by iddata
having count(distinct idtype) = 2;
然而,这也会返回具有其他idtypes的iddata
值(例如12,5,6)。
要使having子句的条件与要检查的实际ID数无关,我会将ID列表移动到CTE中:
with idlist (id) as (
values (12), (5)
)
select iddata
from idtypedata
where idtype in (select id from idlist)
group by iddata
having count(distinct idtype) = (select count(*) from idlist);
要获得那些完全这两个元素的人,可以使用数组进行比较:
with idlist (id) as (
values (12), (5)
)
select iddata
from idtypedata
where idtype in (select id from idlist)
group by iddata
having array_agg(idtype order by idtype) = (select array_agg(id order by id) from idlist);
order by
中的array_agg()
非常重要,因为数组{12,5}
与{5,12}
答案 1 :(得分:1)
使用group by和having。下面的查询为您提供了所有idtype的输出。
select distinct iddata
from idtypedata
group by iddata
having count(distinct idtype) > 1
如果您有任何疑虑,请告诉我们。