Reputation: 25
Suppose I have a database where I keep track of people and their hobbies, and there are two tables: People and Hobbies. Now if there exists a person named Tom from table People with the two hobbies 'fishing' and 'jogging' in table Hobbies, how can I check for other persons who have exactly these two hobbies? I want to exclude people who have, for instance, the hobbies Fishing, Jogging AND Gaming. I have tried the following:
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
And it returns no rows.
Upvotes: 1
Views: 392
Reputation: 164099
Since you have the names of people in the table hobby
you don't need the table people
.
You can group by name_hobbyist
and use the aggregate function string_agg()
in the having
clause to apply the condition:
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'
)
Upvotes: 1