我有一张桌子(见下文),其中包含朋友列表。在每一行中,用户可以是发送者或接收者(请求者/被请求者)。然后状态跟踪他们的关系(状态为1表示他们是朋友)。但是因为uid可以位于发送者或接收者中,所以这让我很烦。
================================
| sender | reciever | status |
--------------------------------
| testusr1 | testusr2 | 1 |
| testusr1 | testusr3 | 1 |
| testusr1 | testusr4 | 0 |
| testusr1 | testusr5 | 1 |
| testusr3 | testusr4 | 1 |
| testusr3 | testusr2 | 1 |
| testusr5 | testusr3 | 1 |
因此,在上面的示例中,testusr1的朋友是:testusr2,testusr3和testusr5。
testusr3的朋友是:testusr5,testusr4,testusr2,testusr1
我正在寻找的查询将获得常见的朋友:testusr2和testusr5
从我在这里得到的另一个答案中清除出来,我以为我可以做一个工会,但是我迷失了大约一半时遵循的逻辑...
SELECT f.uid
FROM(
(SELECT reciever as uid FROM friends where status=1 and sender='$sentuid')
UNION
(SELECT sender as uid FROM friends where status=1 and reciever='$sentuid')
) f
WHERE ...
任何帮助将不胜感激...
最佳答案
尝试类似-(已编辑)
SELECT f.uid
FROM (
SELECT f1.reciever as uid FROM friends f1
WHERE f1.sender = USER1 AND f1.status = 1
UNION
SELECT f2.sender as uid FROM friends f2
WHERE f2.reciever = USER1 AND f2.status = 1
) f
WHERE f.uid IN (
SELECT f3.reciever as uid FROM friends f3
WHERE f3.sender = USER3 AND f3.status = 1 AND f3.reciever != USER1
UNION
SELECT f4.sender as uid FROM friends f4
WHERE f4.reciever = USER3 AND f4.status = 1 AND f4.sender != USER1
);
用要查找普通朋友的2个用户ID替换
USER1
和USER3
sqlfiddle示例-http://sqlfiddle.com/#!2/b0aaf4/8
关于mysql - 查找常见的匹配ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27307259/