LEFT JOIN表A取决于表B.

时间:2014-02-09 01:22:59

标签: mysql sql

我有一个阻止用户系统:

表A:

-------------------
id_user | username 
-------------------
   1    |    A
-------------------
   2    |    B
-------------------
   3    |    C
-------------------
   4    |    D
-------------------

.... and so on

表B:

--------------------------------------
id_block | user_request | user_banned 
--------------------------------------
   1    |       1       |      2
--------------------------------------
   2    |       1       |      3
--------------------------------------
... and so on

案例#1:当用户A从表A获取用户列表时,用户B和用户C对他隐藏。

案例#2:当用户B从表A获取用户列表时,用户A对他隐藏。

案例#3:当用户C从表A获取用户列表时,用户A对其隐藏。

案例#4:当用户D从表A获取用户列表时,它就会获得所有用户。

到目前为止,我已经尝试过这个:

SELECT t1.id_user, t1.username

FROM user t1

  LEFT JOIN block_user t2

    ON (t2.user_request = 1 AND t2.user_banned = 1)

WHERE t1.id_user NOT IN

    (SELECT user_request FROM block_user WHERE user_request = 1 )

  AND t1.id_user NOT IN 

    (SELECT user_banned FROM block_user WHERE user_banned = 1)

结果是用户B和C被隐藏了!大!

但是,当您将用户ID更改为示例2时,则用户A和C隐藏。不太好,应该只是用户A隐藏!

当您将用户ID更改为4时,则用户A,B和C隐藏。

我为这个案例做了一些例子:

sqlfiddle User ID 1

sqlfiddle User ID 2

sqlfiddle User ID 3

sqlfiddle User ID 4

Pd积。我知道,我可以提出两个问题来解决这个问题,但必须有一个解决方案。

1 个答案:

答案 0 :(得分:2)

SELECT t1.id_user, t1.username
FROM user t1
LEFT JOIN block_user t2
ON 
   (t2.user_request = <current user id> AND t2.user_banned = t1.id_user)
   OR
   (t2.user_request = t1.id_user AND t2.user_banned = <current user id>)
WHERE t2.id_block IS NULL;

see the fiddle in action for A, B, C & D