R
R
Roman2017-02-16 17:59:49
MySQL
Roman, 2017-02-16 17:59:49

SQL. Selecting the same values ​​in one column, but different in another. How to implement?

Good afternoon.
There is a table like:
id | user_id | product_id
1 | 1 | 15
2 | 2 | 16
3 | 1 | 16
4 | 2 | 10
5 | 3 | 16
6 | 1 | 15
You need to select products product_id that different users have.
That is, product 16 was bought by user 1,2,3, we select it, and product 15, although it is repeated, was bought by the same user with id 1.
I tried to write something like this:
SELECT product_id FROM basket GROUP BY product_id HAVING count( *)>1;
But there are just single records. I can't make it look for the same product_id, but at the same time with different user_id.
Any help is welcome.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2017-02-16
@true_user

If MySQL can distinct in count, then

SELECT product_id 
FROM basket  
GROUP BY product_id 
HAVING count(distinct user_id)>1

N
nApoBo3, 2017-02-16
@nApoBo3

You can use exists and a subquery, you can take distinct, and then group by and having.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question