2011-04-23 110 views
1

表:使用者(ID INT,姓VARCHAR)MySQL的子查詢變量傳遞

表:阻止列表(ID INT,用戶ID 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」。解決這個問題的最好方法是什麼?

+0

一些示例數據可以幫助您理解您的需求。請張貼3-4位用戶及其阻止關係,以及其中一個或兩個的通緝結果。我有一種感覺,這可以通過'JOIN'和'LEFT JOIN'以更簡單的方式完成,但我不確定你需要得到什麼。 (id,firstname)values(1,tom),(2,dick),(3,harry),(4,john)插入到用戶(id,firstname)中的 – Galz 2011-04-23 11:06:17

+0

; (1,1,2),(2,1,3),(3,1,4),(4,2,3);插入到塊列表(id,userid,blocked_userid)中。 因此,在userid = 1上運行所需的查詢將不會返回任何內容,因爲用戶1已阻止每個人。在userid = 2上運行所需查詢將僅返回用戶4,因爲1阻止了2和2阻止了3,並且查詢不應返回相同的用戶。 – BlackHat 2011-04-26 05:31:01

回答

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