加入一张桌子给自己

时间:2017-04-03 21:05:32

标签: mysql

如何将此表连接到自身以检查两个用户是否同时接受了朋友请求?

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)
);

1 个答案:

答案 0 :(得分:2)

诀窍是user_idfriend_id字段的组合作为友谊表的主键,这些是您自己加入表所需的2个字段。显然,在连接标准中,您必须交叉引用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)