2017-04-03 41 views
2

如何將此表加入自己以檢查兩個用戶是否都接受了好友請求?加入自己的表

mysql> select * from friendships; 
+---------+-----------+----------+ 
| user_id | friend_id | accepted | 
+---------+-----------+----------+ 
|  1 |   2 |  1 | 
|  2 |   1 |  0 | 
|  3 |   1 |  1 | 
|  1 |   3 |  1 | 
|  1 |   4 |  1 | 
|  4 |   1 |  0 | 
|  5 |   1 |  1 | 
|  1 |   5 |  0 | 
+---------+-----------+----------+ 
8 rows in set (0.00 sec) 

並拉出用戶對象。

我可以檢查user 1是否有任何優秀的朋友請求;

mysql> select * from friendships join users on friendships.friend_id = users.id where friendships.user_id = 1 and accepted = false; 
+---------+-----------+----------+----+------------+----------+--------------------+------------------+-----------------+ 
| user_id | friend_id | accepted | id | fullName | username | phone    | verificationCode | accountVerified | 
+---------+-----------+----------+----+------------+----------+--------------------+------------------+-----------------+ 
|  1 |   5 |  0 | 5 | Tom Tester | tom  | +16502222222222222 | 4444    |    1 | 
+---------+-----------+----------+----+------------+----------+--------------------+------------------+-----------------+ 
1 row in set (0.00 sec) 

但我怎麼讓他接受了請求(即user 1user 3都已經接受了該請求)?

另外我有一個用戶表設置在後臺。

編輯:如果它可以幫助

CREATE TABLE friendships (
    user_id int, 
    friend_id int, 
    accepted boolean not null default false, 
    UNIQUE KEY friend (user_id, friend_id) 
); 
+0

你需要爲你的餐桌,使主鍵連接工作按預期這是在你的餐桌 –

+0

AFAIK失蹤這是友誼表的標準模式。 – ARMATAV

+1

如果您使用表的別名,您可以自行加入。就像這樣:SELECT * FROM friendships JOIN友誼AS反向開啓reverse.friend_id = friendships.user_id –

回答

2

訣竅是,user_idfriend_id字段的組合作爲你們的友誼表的主鍵我的模式,這是2場,你需要加入表本身。顯然,在連接標準中,您必須交叉引用2個字段,因爲這兩個記錄中的角色是相反的。

select * 
from friendships f1 
inner join friendships f2 on f1.user_id=f2.friend_id and f1.friend_id=f2.user_id 
where f1.accepted=1 and f2.accepted=a1 and f1.user_id=... 

您也可以通過使用exists子查詢實現相同的輸出:

select * from friendships f1 
where f1.user_id=... and f1.accepted=1 
    and exists (select 1 from friendships f2 
       where f2.user_id=f1.friend_id and f1.friend_id=f1.user_id and f2.accepted=1) 
+0

你是上帝。我對我所要做的事情感到非常困惑 - 我只使用過通過其他表格進行比較的表格,而沒有將表格與自己進行比較。多謝,夥計!在你的第一個例子中,'f2.accepted = a1'應該是'f2.accepted = 1'或'= true' - 還有一個額外的'a'字符。 <3 – ARMATAV

+0

也爲了完成目的,在前面應該有一個'加入f1.friend_id = users.id'上的用戶,這解決了'拉出用戶對象'部分問題:D – ARMATAV