以下是我的表格:
1):表朋友:
id_invitation
id_exp
id_des
date_invitation
active
2):表用户:
id
prenom
nom
email
password
我有两个问题:
1:第一个返回我的朋友列表。
SELECT *
FROM users U
JOIN friends F
ON ( U.id = F.id_exp AND F.id_des = :id )
OR ( U.id = F.id_des AND F.id_exp = :id )
WHERE U.id <> :id
AND F.active = 1
2:第二个只返回两个用户之间的共同朋友。
SELECT u.id
, u.nom
, u.prenom
FROM users u
JOIN
( SELECT id_exp
, id_des
FROM friends
WHERE id_exp IN(:id_exp, :id_des)
AND active = 1
UNION
SELECT id_des
, id_exp
FROM friends
WHERE id_des IN(:id_exp, :id_des)
AND active = 1
) tmp
ON tmp.id_des = u.id
GROUP
BY u.id
HAVING COUNT(*) = 2
小修正:
1是2和3之间的普通朋友,因为他是2和3的朋友(如果你想在2和3收集共同的朋友,你将有1)。 4是2的朋友,但不是3。 而且3也是5和6的朋友,我想在2的朋友列表中搜索,从2恢复朋友但是他们不是3的朋友(在这种情况下是4)。 我想只返回4而不是4,5,6
更多信息: 我希望当3次访问2的不常见朋友列表时,它会看到4。 我想只返回2个与4不友好的朋友。
我解释它有点麻烦。
我尝试过这段代码:
SELECT
*
FROM
users U
INNER JOIN friends F
ON ( U.id = F.id_exp AND F.id_des = :id )
OR ( U.id = F.id_des AND F.id_exp = :id )
WHERE
(U.id <> :id_k
AND F.active = 1)
AND NOT IN
(SELECT u.id,
u.nom, u.prenom, u.avatar
FROM users u
INNER JOIN
(
SELECT id_exp, id_des
FROM friends
WHERE id_exp IN(:id_exp, :id_des)
AND active = 1
UNION
SELECT id_des, id_exp
FROM friends
WHERE id_des IN(:id_exp, :id_des)
AND active = 1
) tmp ON tmp.id_des = u.id
GROUP BY u.id
HAVING COUNT(*) = 2)
但它在最坏的情况下不起作用,它会产生错误,并且不会出现相关页面的部分。 谢谢。
答案 0 :(得分:0)
我相信你已经拥有使用当前查询所需的共同和非共同状态所需的成分,这只是你现在如何使用它的问题。
SELECT
u.id
, u.nom
, u.prenom
, case when count(tmp.id_des) = 1 then 'Not Mutual'
when count(tmp.id_des) = 2 then 'Mutual'
when count(tmp.id_des) = 0 then 'Alone in this world'
else 'Undefined'
end as friend_status
FROM users u
JOIN
( SELECT id_exp
, id_des
FROM friends
WHERE id_exp IN(:id_exp, :id_des)
AND active = 1
UNION
SELECT id_des
, id_exp
FROM friends
WHERE id_des IN(:id_exp, :id_des)
AND active = 1
) tmp ON tmp.id_des = u.id
GROUP BY
u.id
, u.nom
, u.prenom