2013-08-26 70 views
0

我有一個多對多的表,它跟蹤友誼。與朋友的多對多關係

我需要知道,兩個朋友批准對方。

例如,當一個人要求成爲朋友時,他們的id將被放入self_uuid中,並且朋友將被放入friend_uuid中。當朋友批准請求時,發生同樣的事情,只是相反。

enter image description here

如何找到那些相互認可對方所有的人? 我如何找到所有未互相批准的人?

回答

3

互認:

select f1.self_uuid, f1.friend_uuid 
from friends f1 
join friends f2 on f1.self_uuid = f2.friend_uuid and f1.friend_uuid = f2.self_uuid 

朋友的請求沒有被批准:

select f1.self_uuid, f1.friend_uuid 
from friends f1 
left join friends f2 on f1.self_uuid = f2.friend_uuid and f1.friend_uuid = f2.self_uuid 
where f2.self_uuid is null 
+0

哇感謝這麼多!這個查詢是否比較昂貴,性能明智嗎? – stackOverFlew

+0

如果您在兩欄中都有複合索引,則表現應該很好。 – Barmar