我有一个 MySQL 表:
Friends
--------
fr_id
user_id_a
user_id_b
approval_status
---------
其背后的基本逻辑是,如果用户 #1 向好友 #2 发送好友请求,则表条目将如下所示:
------------------------------------------------
fr_id - user_id_a - user_id_b - approval_status
1 1 2 no
------------------------------------------------
现在只有当用户批准请求时,他们才会成为朋友。
要选择对用户 #1 的所有请求,我可以使用以下查询:
SELECT * FROM friendship
WHERE
approved_status='no'
AND
(user_id_a = 1 OR user_id_b = 1)
结果将如下所示:
fr_id - user_id_a - user_id_b - approval_status
1 1 2 no
如何区分当前用户是否是user_id_a
我user_id_b
可以使用另一个 ID 从另一个表中提取他们的信息的用户?
由@aweis 提供的答案
SELECT * ,
CASE WHEN user_id_a =3
THEN 'a'
ELSE 'b'
END AS UserIdColumn,
CASE WHEN user_id_a =3
THEN user_id_b
ELSE user_id_a
END AS NotCurrentUserID
FROM fr_friendship
WHERE approved_status = 'yes'
AND (
user_id_a =3
OR user_id_b =3
)
我可以选择朋友,但我留下的问题的第二部分是加入,然后用另一个表来获取朋友的用户名......我试过这个,但它给了我错误..
#1054 - Unknown column 'NotCurrentUserID' in 'on clause'
SELECT f.*, p.username AS friend,
CASE WHEN user_id_a = 1 THEN 'a'
ELSE 'b'
END AS UserIdColumn,
CASE WHEN f.user_id_a = 1 THEN f.user_id_b
ELSE f.user_id_a
END AS NotCurrentUserID
FROM fr_friendship AS f
LEFT JOIN u_profile AS p ON p.user_id_login = NotCurrentUserID
WHERE
f.approved_status = 'yes'
AND
(f.user_id_a = 1 OR f.user_id_b = 1)
编辑:解决方案
我设法解决了它....我希望它可以帮助某人:
SELECT a.friend_id, u.username
FROM
( SELECT CASE WHEN user_id_a = 1
THEN user_id_b
ELSE user_id_a
END AS friend_id
FROM fr_friendship
WHERE approved_status = 'yes' AND (user_id_a = 1 OR user_id_b = 1)
) AS a
LEFT JOIN u_profile AS u ON u.user_id_login = a.friend_id