2013-10-13 48 views
0


排除所有被阻止的用戶我有點卡住了MySQL查詢:MySQL的 - 從結果

我有表用戶

 
user_id|language|name 
1  |en  |Mike 
2  |en  |John 
3  |en  |Jesse 
4  |de  |Wolfgang (Me) 

和表users_blocked

 
user_id|blocked_user_id 
1  |4 
4  |1 
1  |3 
3  |1 
4  |2 

(其中 user_id已經封鎖 blocked_user_id

我想找到的所有用戶(不包括我自己)誰講英語(en),我沒有阻止他們,他們沒有阻止我。 它應該只返回上面例子中ID爲3的用戶。

我正在構建語言合作伙伴搜索,它從結果中排除所有被阻止的用戶(兩種方式)。

回答

2

這裏,給這個一展身手:

select * from users where user_id <> 4 and language = 'en' 
    and user_id not in(select blocked_user_id from users_blocked where user_id = 4) 
    and user_id not in(select user_id from users_blocked where blocked_user_id = 4) 

演示在這裏:http://sqlfiddle.com/#!2/b22a4/2

+0

使用*不是很好,除非它是必要的! –

+0

謝謝,工作完美! –

+0

是在這個數據集..它不會縮放,如果你有很多記錄..檢查「視圖執行計劃」這些依賴子查詢和全是壞消息的可伸縮性 –

1
SELECT users.user_id, users.language, users.name 
FROM users 
WHERE users.language = 'EN' 
    AND NOT EXISTS(SELECT * 
       FROM users_blocked 
       WHERE (users_blocked.user_id = 4 
         AND users_blocked.blocked = users.user_id) 
        OR (users_blocked.blocked = 4 
         AND users_blocked.user_id = users.user_id) 
       )