A
A
alex995052018-11-08 19:17:45
MySQL
alex99505, 2018-11-08 19:17:45

What is the best way to get symmetrical data in a table?

Hello!
Let's say there is a friends table with fields id, user_id1, userd_id2, which indicates who is friends with whom.
What is the fastest way to execute a SQL query to get all people from the list who are friends with each other?
For example, there is such data
id user_id1 userd_id2
1 10 20
2 11 20
3 20 10
It is necessary that only the first and third rows be returned in the query

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexalexes, 2018-11-08
@alexalexes

Elementary, join the same table on itself.

select *
from t as t1
join t as t2 on t1.user_id1 = t2.user_id2
                 AND t2.user_id1 = t1.user_id2

A
Anton Anton, 2018-11-08
@Fragster

select user_id1, user_id2 from (
Select 
user_id1, user_id2, 1 as flag
union all
Select 
user_id2, user_id1, -1
) as t
group by user_id1, user_id2
having sum(flag) = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question