2017-06-02 76 views
2

我有一個表有三列ID,follower_id,following_id和我只有一個的ID 或現在我想的記錄假設user1後續到user2user2後續到user1在一個查詢如何獲得記錄單查詢

表結構

---------------------------------- 
|id | follower_id | following_id | 
---------------------------------- 
|1 | 101  | 105   | 
|2 | 105  | 102   | 
|3 | 105  | 101   | 
|4 | 105  | 103   | 
---------------------------------- 

結果應該是1 - > 101 - > 105或3-> 105-> 101

+1

什麼是這個問題? – Jens

+0

我希望這些結果(結果應該是1 - > 101 - > 105或3-> 105-> 101)來自上表。 –

+0

爲什麼你需要這樣的結果? '[101,105]'具有相同的信息。 –

回答

3

如果你想去的地方追蹤者和追蹤匹配,你可以使用自加入

select t1.* from my_table as t1 
inner join my_table as t2 
where t1.follower_id = t2.following_id 
and t1.following_id = t2.follower_id 
0

可以使用leastgreatest做到這一點。

select * from t 
where (least(follower_id,following_id),greatest(follower_id,following_id)) 
in (select least(follower_id,following_id),greatest(follower_id,following_id) 
    from t 
    group by least(follower_id,following_id),greatest(follower_id,following_id) 
    having count(*) > 1) 
0

可能是這樣的查詢將幫助你行....

SELECT * 
FROM Yourtable A 
WHERE EXISTS (SELECT 1 FROM Yourtable B WHERE B.follower = A.following) 
AND EXISTS (SELECT 1 FROM Yourtable C WHERE C.following = A.follower)