SQL Server 2000奇怪的子查询问题
有一种奇怪的行为让我发疯。
我在旧的 SQL Server 2000 数据库中有一个用户表和一个权限表。 这个数据库一团糟,很多表没有PK,表之间没有关系......但我无法修复它(老实说,我不认为这与我遇到的问题有关)。
Users:
IDRecord -> PK money
-- other fields
Permissions:
IDRecord -> money (is not a PK)
IDUser -> money (refers to Users.IDRecord WITHOUT FK)
Function -> varchar
-- other fields
我想在没有任何许可的情况下获取用户的用户ID。
我的第一个方法是写一些东西:
select distinct IDRecord
from Users
where IDRecord not in (
select IDUser from Permissions
)
不返回任何行。
但我知道有些用户没有权限,所以我编写了第二个查询:
select distinct U.IDRecord
from Users U
left join Permissions P
on P.IDUser = U.IDRecord
where P.IDRecord is null
正确返回没有权限的用户。
那么,问题出在哪里呢?
为什么第一个不起作用?
There's a strange behaviour that is drive me crazy.
I've a table of users and a table of permissions in an old SQL Server 2000 database.
This database is a mess, many tables have no PK and there are no relations between the tables... but I couldn't fix it (and honestly I don't think this is related to the problem I have).
Users:
IDRecord -> PK money
-- other fields
Permissions:
IDRecord -> money (is not a PK)
IDUser -> money (refers to Users.IDRecord WITHOUT FK)
Function -> varchar
-- other fields
I want to get the User's ids of the users without any permission.
My first approach was to write something as:
select distinct IDRecord
from Users
where IDRecord not in (
select IDUser from Permissions
)
That returns me no rows.
But I KNOW there are users without permissions, so I write a second query:
select distinct U.IDRecord
from Users U
left join Permissions P
on P.IDUser = U.IDRecord
where P.IDRecord is null
that correctly returns the users without permissions.
So, where's the problem?
Why the first doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是预期的行为。
这是预期的,因为 SQL 具有三值逻辑。
换句话说:对于那些没有权限的用户,子查询不会返回任何结果(NULL)。
在这些情况下,您的
WHERE
条件不满足,因为值永远不能等于或不等于 NULL。替代方案:
1)使用
LEFT JOIN
(正如您所做的那样),或者2) 使用
NOT EXISTS
,例如:编辑:如果您不小心,3VL 将如何咬您的更多详细信息:
如果您执行以下操作,可能会出现违反直觉的结果...
突然,
a_column
为 NULL 的行从您的结果中消失。要找回它们,您可以这样做:
This is expected behavior.
It is expected because SQL has three-valued logic.
In other words: for those users who have no permissions, there is no result (NULL) returned by your subquery.
Your
WHERE
condition is not satisfied in those cases because a value can never equal nor not equal NULL.Alternatives:
1) use a
LEFT JOIN
(as you have done), or2) use
NOT EXISTS
, e.g.:Edit: More detail on how 3VL can bite you if you're not careful:
A possibly counter-intuitive result occurs if you do something like this...
Suddenly rows where
a_column
is NULL disappear from your results.To get them back you can do this: