Answer the question
In order to leave comments, you need to log in
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
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
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 questionAsk a Question
731 491 924 answers to any question