Mysql 将一张桌子连接到它自己
我如何将此表加入到自身中,以检查两个用户是否都接受了好友请求Mysql 将一张桌子连接到它自己,mysql,Mysql,我如何将此表加入到自身中,以检查两个用户是否都接受了好友请求 mysql> select * from friendships; +---------+-----------+----------+ | user_id | friend_id | accepted | +---------+-----------+----------+ | 1 | 2 | 1 | | 2 | 1 | 0 | |
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 1
和user 3
都接受了请求)
我还在后台设置了一个用户表
编辑:我的模式(如果有帮助)
CREATE TABLE friendships (
user_id int,
friend_id int,
accepted boolean not null default false,
UNIQUE KEY friend (user_id, friend_id)
);
诀窍在于,
user\u id
和friend\u id
字段的组合作为友谊表的主键,这两个字段是加入表本身所需的两个字段。显然,在连接条件中,您必须交叉引用这两个字段,因为角色在这两个记录中是颠倒的
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)
您的表需要有一个主键,才能使联接按预期工作,这是tableAFAIK中缺少的,这是友谊表的标准架构。如果您对表使用alias,则可以使用self联接。类似于以下内容:选择*FROM friendships JOIN friendships AS reverse ON reverse.friends\u id=friendships.user\u id以较小的步骤开始-通常如何连接两个表?你不必在你的桌子上有一个PK,但你这样做是非常可取的。这样,MySQL将创建一个隐藏的主键。最糟糕的是你不能使用它。@N.B.用户id和朋友id字段的组合确实是上表中的主键。你是上帝。我对自己要做的事情感到非常困惑——我只处理过通过其他表格进行比较的表格,从未将同一张表格与自身进行过比较。谢谢你,伙计!同样在第一个示例中,
f2.accepted=a1
应该是f2.accepted=1
或=true
-还有一个额外的字符。此外,为了完成,f1上应该有一个加入用户。friend\u id=users.id
就在前面,它解决了问题的“拉出用户对象”部分:D