我的表是这样定义的:
名称也是字符串和属性。
ID | Name | Property
该表中的数据示例如下:
ID | Name | Property
1 Peter Newsletter
2 Paul Register
3 Peter Register
4 Shaun Newsletter
5 Steve Register
现在,我想查询所有拥有房地产通讯的人并进行注册。结果,我应该得到彼得,因为他拥有这两个财产。
因此,结果表应如下所示:
ID | Name | Property
1 Peter Newsletter
3 Peter Register
因此,我要查询的所有内容都是哪个人同时拥有房地产的新闻通讯和注册信息。
这是一种方法:
select t.*
from table t
where exists (select 1
from table t2
where t2.name = t.name and t2.property = 'NewsLetter'
) and
exists (select 1
from table t2
where t2.name = t.name and t2.property = 'Register'
);
如果您只想要名称列表(可能带有id
s),我可以这样做:
select t.name
from table t
where t2.property in ('NewsLetter', 'Register')
group by t.name
having count(distinct property) = 2;
如何获取id
s的列表取决于您的数据库,如listagg()
orgroup_concat()
或or string_agg()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句