Michel Andrade Michel Andrade - 6 months ago 14
SQL Question

SQL - Check if IDs contains same ID's value

I wonder how can I check if two users (user_id) are in the same thread (thread_id) without passing the (thread_id) using SQL, through the structure of the table below.

enter image description here

Answer

To get all threads where those 2 users are in you can do

select thread_id
from your_table
where user_id in (1,2)
group by thread_id
having count(distinct user_id) = 2

To get all threads that have more than one user do

select thread_id
from your_table    
group by thread_id
having count(distinct user_id) >= 2