This is my database design:
CREATE TABLE post (
id INT,
user_id INT,
type_id INT
);
I want to get a list of users who wrote posts of types 1 and 2 only. This seems to be working:
select distinct user_id
from post p1
where exists
(
select 1
from post p2
where p1.user_id = p2.user_id
and type_id = 1
)
and exists
(
select 1
from post p2
where p1.user_id = p2.user_id
and type_id = 2
)
and not exists
(
select 1
from post p2
where p1.user_id = p2.user_id
and type_id not in (1,2)
)
I have a feeling this can be done easier. Any ideas?
2
Answers
There are quite a few ways to do it with GROUP BY and HAVING.
Here are a few…
Or using set operators…
Since you mentioned your query returns correct answer, I compared output of my query against yours and it matches, let me know if you observe any differences, I can edit the answer.
To test the case, I have entered 3 sets of data,
Here is the fiddle