开发者

MySQL subquery variable passing

table: User (id INT, firstname VARCHAR)

table: Blocklist (id INT, userid INT, blocked_userid INT)

SELECT user.id theID, user.firstname
FROM user
WHERE
NOT user.id = 1000
AND IF ((SELECT id FROM blocklist WHERE theID = ANY (SELECT blocked_userid FROM blocklist WHERE userid = 1000)), 0, (IF ((1000 = ANY (SELECT userid FROM blocklist WHERE blocked_userid = theID)),0,1)))

I want to return a list of all users not the current user, say... user 1000, that isn't blocked by that user or that isn't on the blocklist of another user. Therefor it's a two-way system... you can't see people you blocked and you can see people who blocked you. Problem is, I can't very well use开发者_Python百科r "theID" in the subquery. What would be the best way to tackle this?


Ok, based on the sample data I think this does it:

SELECT u.id, u.firstname, b1.id, b2.id
FROM user AS u
JOIN user myUser ON myUser.id = 2
LEFT JOIN blocklist b1 ON u.id = b1.userid AND b1.blocked_userid = myUser.id
LEFT JOIN blocklist b2 ON u.id = b2.blocked_userid AND b2.userid = myUser.id
WHERE u.id != myUser.id
HAVING b1.id IS NULL AND b2.id IS NULL

If you really need to get rid of the two extra columns b1.id and b2.id:

SELECT t.theId, t.firstname FROM
       (SELECT u.id as theID, u.firstname, b1.id as b1, b2.id as b2
       FROM user AS u
       JOIN user myUser ON myUser.id = 2
       LEFT JOIN blocklist b1 ON u.id = b1.userid AND b1.blocked_userid = myUser.id
       LEFT JOIN blocklist b2 ON u.id = b2.blocked_userid AND b2.userid = myUser.id
       WHERE u.id != myUser.id
HAVING b1.id IS NULL AND b2.id IS NULL) as t
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜