我有一个包含userid和follow列的关注表,我有一个带有userid和username的用户表。
我希望能够选择关注说用户4的用户,但是在同一个选择查询中有一列可以调用followornot,如果用户4不跟随被选中的人,则该值为0;如果用户4跟随,则为1选定的用户。
我心中有这样的东西,但它没有按预期工作。
查询如下
SELECT
u.username,
u.userid,
(case when following= '4' then 1 else 0 end) as followornot
FROM user u inner JOIN followTable f ON f.userid = u.userid
WHERE f.following = '4'
样本记录:
用户
╔════════╦══════════╗
║ USERID ║ USERNAME ║
╠════════╬══════════╣
║ 1 ║ john ║
║ 2 ║ jane ║
║ 3 ║ smith ║
║ 4 ║ paul ║
╚════════╩══════════╝
FollowTable
╔════════╦═════════════╗
║ USERID ║ FOLLOWINGID ║
╠════════╬═════════════╣
║ 1 ║ 2 ║
║ 4 ║ 1 ║
║ 3 ║ 4 ║
║ 1 ║ 4 ║
╚════════╩═════════════╝
答案 0 :(得分:1)
SELECT u.*,
(d.followingID IS NULL) followornot
FROM user u
INNER JOIN followTable f
ON u.userID = f.userID
LEFT JOIN followTable d
ON u.userid = d.followingID AND
d.userID = 4
WHERE f.followingid = 4
输出
╔════════╦══════════╦═════════════╗
║ USERID ║ USERNAME ║ FOLLOWORNOT ║
╠════════╬══════════╬═════════════╣
║ 1 ║ john ║ 0 ║
║ 3 ║ smith ║ 1 ║
╚════════╩══════════╩═════════════╝
答案 1 :(得分:0)
为什么你不这样做:
select u.id, f.key_user, key_follower FROM user u INNER JOIN is_following f ON u.id=f.key_user AND f.key_follower=4;
其中u.id是user-id,key_user是fk in is_following,key_follower是user_id后跟user-id。