MySQL子查询变量传递

时间:2011-04-23 05:40:41

标签: mysql variables scope subquery

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)))

我想返回所有用户的列表,而不是当前用户,例如...用户1000,该用户未被该用户阻止或不在另一个用户的阻止列表中。因此,这是一个双向系统...你看不到你被阻止的人,你可以看到阻止你的人。问题是,我不能很好地在子查询中使用“theID”。解决这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

好的,基于样本数据,我认为这样做:

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

如果你真的需要摆脱两个额外的列b1.id和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