I had a table:
----------------------
| user_id | marker_id|
----------------------
| 1 | 1 |
--------
| 1 |2 |
--------
| 2 |1 |
--------
| 2 |2 |
--------
| 2 |3 |
--------
| 3 |1 |
--------
I want get unique user_id has marker_id =(1,2). Don't get user_id has marker_id = (1,2,3). How to get user_id = 1 and not include user_id =2.
select distinct user_id
from table_name
where marker_id in (1,2)
One method uses group by
:
select user_id
from t
group by user_id
having sum(marker_id = 1) > 0 and
sum(marker_id = 2) > 0 and
sum(marker_id not in (1, 2)) = 0;
Each condition in the having
clause tests one of the values. The first tests for marker_id = 1
and the > 0
says there is at least one. The second similarly tests for marker_id = 2
. The third says that there are no other marker ids.
I call this type of query a "set-within-sets" subquery (you are looking for marker ids for each user). I find that group by
/ having
is a flexible way to solve these queries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.