0

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.

2 Answers 2

1
select distinct user_id 
from table_name 
where marker_id in (1,2)
Sign up to request clarification or add additional context in comments.

2 Comments

But result include user_id =2. I only want get marker_id in (1,2) and total_marker_id = 2. It means user_id has exactly marker_id = (1,2) not more (1,2,3,4)
please add your expected result in your question
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.