假设我有一个数据库,在那里我可以跟踪人们及其爱好,并且有两个表:people和hobbies。现在,如果桌上有一个叫汤姆的人,桌上有两个爱好"钓鱼"one_answers"慢跑",我该如何查找其他有这两个爱好的人?例如,我想排除那些有钓鱼、慢跑和游戏爱好的人。我尝试过以下几种:
select name
from people
where name IN(
select name_hobbyist
from hobby
where hobby IN(
select hobby
from hobby
where name_hobbyist =(
select name
from people
where name = 'Tom'
)
)
)
order by name asc
并且它不返回任何行。
由于表hobby
中有人名,因此不需要表people
您可以group by name_hobbyist
并使用having
子句中的聚合函数string_agg()
来应用条件:
select name_hobbyist
from hobby
where name_hobbyist <> 'Tom'
group by name_hobbyist
having string_agg(hobby, ',' order by hobby) = (
select string_agg(hobby, ',' order by hobby)
from hobby
where name_hobbyist = 'Tom'
)