SQL JOIN-当前用户未阻止的用户选择

时间:2015-06-06 19:51:56

标签: sql inner-join

SELECT * FROM User
INNER JOIN BlockUser ON BlockUser.userId='1' and User.userId != BlockUser.blockID

我有两个表格是“用户”表和 BlockUser 表。

我需要从用户表中选择除特定用户阻止的用户

之外的所有用户

用户表

userID  userName  nickName
1       abc       abc
2       adc       adc
3       dc        dc
4       xyz       xyz
5       qwe       qwe

BlockUser

_Id  userId  blockID
1      1       2
2      1       3

结果

userID  userName  nickName
4       xyz       xyz
5       qwe       qwe

请帮我纠正我的Sql查询。

4 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @blocker int = 1
SELECT * FROM [User]
WHERE [User].userID NOT IN (SELECT BlockUser.blockID FROM BlockUser WHERE BlockUser.blockID = [User].userID AND BlockUser.userID = @blocker)
AND userID <> @blocker

http://sqlfiddle.com/#!3/a7012/14

错误也是SQL关键字,它是表的名称,更改表用户的名称或使用括号如图所示。

还有其他解决方案(来自其他用户但已删除):

select u.*
from [User] u
left join BlockUser bu on bu.blockID = u.userID
                      and bu.userId = 1
where bu.userID is null
      and u.userID <> 1;

select * from [user]
where userID <> 1
and userID not in 
  (select blockID from BlockUser 
   where userID = 1);

编辑1:修正查询
编辑2:钉它 - 不是:)
编辑3:考虑使用变量
从结果中删除阻止程序 编辑4:添加了其他解决方案

答案 1 :(得分:0)

您的查询如下: 从userID NOT IN的用户中选择userID,userName,nickName(从BlockUser中选择blockID,其中userId = 1);

答案 2 :(得分:0)

将连接类型更改为外连接,然后过滤用户表以获取非空记录。

答案 3 :(得分:0)

select * from user 
where userId <> '1'
and userid not in 
  (select blocked from BlockUser.userId 
   where userId = '1')