[英]“NOT IN” not working as expected
I was writing a query to find the node type from the table BST ordered by the value of the node. 我正在编写一个查询,以从按节点值排序的表BST中查找节点类型。 table, BST, had two columns N and P, where N represents the value of a node in BST, and P is the parent of N. say, BST has following records: BST Table
表BST具有两个列N和P,其中N表示BST中节点的值,P是N的父级。例如,BST具有以下记录: BST表
I successfully executed the query as follows: 我成功执行了查询,如下所示:
SELECT n,CASE
WHEN p IS NULL THEN 'Root'
WHEN n IN (SELECT DISTINCT p FROM BST) THEN 'Inner'
ELSE 'Leaf'
END
FROM BST
ORDER BY n;
Result: Result as expected 结果: 预期结果
But instead of using "IN", when I tried the same query using "NOT IN" as given below: 但是,当我尝试使用以下给出的“ NOT IN”进行相同的查询时,而不是使用“ IN”:
SELECT n,CASE
WHEN p IS NULL THEN 'Root'
WHEN n NOT IN (SELECT DISTINCT p FROM BST) THEN 'Leaf'
ELSE 'Inner'
END
FROM BST
ORDER BY n;
it didn't work as expected. 它没有按预期工作。 Why so?
为什么这样?
As @jarlh suggested, use NOT EXISTS, or when using NOT IN, be sure to exclude NULLs from your subquery like: 正如@jarlh所建议的,请使用NOT EXISTS,或者在使用NOT IN时,请确保从子查询中排除NULL,例如:
SELECT n,CASE
WHEN p IS NULL THEN 'Root'
WHEN n NOT IN (SELECT DISTINCT p FROM BST WHERE p IS NOT NULL) THEN 'Leaf'
ELSE 'Inner'
END
FROM BST
ORDER BY n;
If I were you, I'd just a NOT EXISTS. 如果我是你,我只是一个不存在。 I used to always use NOT IN as a beginner.
我以前总是以NOT IN作为初学者。 Later on I realized that you need to consider quite a bit of different factors that you never thought of at first.
后来我意识到,您需要考虑很多您一开始从未想到的不同因素。 Use WHERE NOT EXISTS and you'll be happy fellow.
使用WHERE NOT EXISTS,您会很高兴的。
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.