2010-08-24 46 views
2

heh guys,
我需要MySQL Query的幫助。該查詢的輸出應該是這樣的MySQL查詢幫助

User1  User2 
xxx1  xxx2 
xxx3  xxx1 

但不

User1  User2 
xxx1  xxx2 
xxx2  xxx1 

等。

我需要不同用戶之間的所有「友誼」。友情存在,即當

UserId 8 exists in Column User1_id 
UserId 4 exists in Column User2_id 
**AND** 
UserId 8 exists in Column User2_id 
UserId 4 exists in Column User1_id 

在此先感謝!

友誼表

+----------+----------+ 
| User1_id | User2_id | 
+----------+----------+ 
|  8 |  4 | 
|  4 |  8 | 
|  29 |  4 | 
|  4 |  10 | 
|  10 |  4 | 
|  8 |  37 | 
|  4 |  29 | 
|  37 |  8 | 
|  37 |  4 | 
|  29 |  8 | 
|  4 |  37 | 
|  8 |  10 | 
|  8 |  29 | 
|  4 |  40 | 
|  40 |  4 | 
|  40 |  29 | 
|  29 |  40 | 
+----------+----------+ 

用戶表

+----+-----------------------------+ 
| id | username     | 
+----+-----------------------------+ 
| 4 | hhessel      | 
| 8 | xxx1      | 
| 10 | xxx2      | 
| 29 | xxx3      | 
| 40 | xxx4      | 
| 37 | xxx5      | 
| 39 | xxx6      | 
+----+-----------------------------+ 

回答

2

用途:

SELECT a.user1_id, 
     a.user2_id 
    FROM FRIENDSHIP a 
    JOIN FRIENDSHIP b ON b.user2_id = a.user1_id 
        AND b.user1_id = a.user2_id 
        AND b.user1_id > a.user1_id 

你必須,如果你想要的列值反向扭轉user1_id比較:

AND b.user1_id < a.user1_id 
+0

很好的解決方案。工作正常:)完全忘記了一個可能的自我加入。 – 2010-08-24 22:18:03

+0

@Henrik P. Hessel:它是返回一行而不是一對的'b.user> a.user'。 – 2010-08-24 22:19:20

+0

試圖瞭解b.user> a.user,但似乎很晚;) – 2010-08-24 22:25:28

1

你可以試試:

select u1.username un0, u2.username un1 
    from friendship f inner join user u1 on f.user1_id = u1.id 
inner join user u2 on f.user2_id = u2.id 
    left join 
    (
    select u2.username un0, u1.username un1 
     from friendship f inner join user u1 on f.user1_id = u1.id 
     inner join user u2 on f.user2_id = u2.id 
    ) b using (un0, un1) 
where un0 is null 

不知道是否會工作。

1

這應該讓你去:

SELECT f1.user1_id, f1.user2_id 
FROM  friendship f1 
LEFT JOIN friendship f2 ON f1.user1_id = f2.user2_id AND f1.user2_id = f2.user1_id 
WHERE  f1.user1_id = f2.user2_id 

如果您需要實際的用戶名等,您可以隨時加入用戶表。

+0

OMG小馬,你打敗了我......並且你保持id與「b.user1_id> a.user1_id」的唯一性。尼斯。 – Shoeless 2010-08-24 22:16:08