SQL JOIN- 未被当前用户屏蔽的用户选择
SQL JOIN- user selection which are not blocked by current user
SELECT * FROM User
INNER JOIN BlockUser ON BlockUser.userId='1' and User.userId != BlockUser.blockID
我有两个 table 一个是“Users” table 和 BlockUser table.
我需要 select 来自用户 table 的所有用户,特定用户阻止的用户除外
用户table
userID userName nickName
1 abc abc
2 adc adc
3 dc dc
4 xyz xyz
5 qwe qwe
阻止用户
_Id userId blockID
1 1 2
2 1 3
结果
userID userName nickName
4 xyz xyz
5 qwe qwe
请帮助我更正我的 Sql 查询。
试试这个:
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 关键字,它是 table 的名称,请更改 table 用户的名称或使用括号,如图所示。
还有其他解决方案(来自其他用户但已删除):
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: 添加了其他解决方案
您的查询如下:
select userID,userName,nickName from Users where userID NOT IN(Select blockID from BlockUser where userId =1 );
将联接类型更改为外部联接,然后过滤用户 table 以获取非空记录。
select * from user
where userId <> '1'
and userid not in
(select blocked from BlockUser.userId
where userId = '1')
SELECT * FROM User
INNER JOIN BlockUser ON BlockUser.userId='1' and User.userId != BlockUser.blockID
我有两个 table 一个是“Users” table 和 BlockUser table.
我需要 select 来自用户 table 的所有用户,特定用户阻止的用户除外
用户table
userID userName nickName
1 abc abc
2 adc adc
3 dc dc
4 xyz xyz
5 qwe qwe
阻止用户
_Id userId blockID
1 1 2
2 1 3
结果
userID userName nickName
4 xyz xyz
5 qwe qwe
请帮助我更正我的 Sql 查询。
试试这个:
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 关键字,它是 table 的名称,请更改 table 用户的名称或使用括号,如图所示。
还有其他解决方案(来自其他用户但已删除):
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: 添加了其他解决方案
您的查询如下: select userID,userName,nickName from Users where userID NOT IN(Select blockID from BlockUser where userId =1 );
将联接类型更改为外部联接,然后过滤用户 table 以获取非空记录。
select * from user
where userId <> '1'
and userid not in
(select blocked from BlockUser.userId
where userId = '1')