我有两张桌子
friends
表:
users
表:
并希望得到两个用户的共同朋友的名字(nom)。即: 1是2的朋友; 3是1和2的朋友。
用户1和2有共同的朋友3.我想得到他的名字' sammy'在一个查询中。
我该怎么做?
答案 0 :(得分:0)
排除date_confirmation
检查的逻辑,您有f1_id
和f2_id
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_exp=$f2_id AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_exp=$f1_id
)
这只会检查 ONE 方向。两者都邀请了同一个朋友。更复杂的部分是让另一个朋友邀请他们中的一个(圆形邀请!)
对于完整的循环答案,有4个条件。您需要在每个之间执行UNION
。
除了您使用id_exp
和id_des
以及$f1_id
和$f2_id
这是第二个:
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_exp=$f2_id AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_exp=$f1_id
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_des=$f2_id AND
f.id_exp IN (
SELECT id_exp
FROM friends
WHERE id_des=$f1_id
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_des=$f2_id AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_exp=$f1_id
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_exp=$f2_id AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_des=$f1_id
)
不容易测试,但这是概念。然后你必须消除重复: - )
答案 1 :(得分:0)
我试过这段代码:
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_exp=445 AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_exp=400
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_des=445 AND
f.id_exp IN (
SELECT id_exp
FROM friends
WHERE id_des=400
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_des=445 AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_exp=400
)
UNION DISTINCT
SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE
f.id_exp=445 AND
f.id_des IN (
SELECT id_des
FROM friends
WHERE id_des=400
)
他告诉我:enter image description here 这是ma表朋友:enter image description here 查看朋友表的最后三行。
当我交换两个数字的位置时,它给了我另一个结果。 我认为代码不正确。 你怎么看? 感谢。