首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在sql server中没有在运算符中工作。

在sql server中没有在运算符中工作。
EN

Stack Overflow用户
提问于 2018-05-10 04:52:33
回答 4查看 784关注 0票数 6

我在解决黑客队伍二叉树question.PFB的问题

给出了一个表BST,包含两个列: N和P,其中N表示二叉树中节点的值,P是N的父列。

编写查询,查找按节点值排序的二叉树节点类型。为每个节点输出以下内容之一:

代码语言:javascript
运行
复制
Root: If node is root node.
Leaf: If node is leaf node.
Inner: If node is neither root nor leaf node.

我能够使用下面的查询来解决这个问题

代码语言:javascript
运行
复制
select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner' else 'Leaf'
end
from BST order by n

但在此之前,我尝试了下面的查询,但它不起作用

代码语言:javascript
运行
复制
select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner'
 when p is not null and (n not in (select p from BST)) then 'Leaf'
end
from BST order by n

上面的查询给出了根注释和内部节点,但是它不是叶,而是空的,请有人解释一下它为什么会显示这种行为。

你可以试试这里这个问题

谢谢你

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-05-10 05:11:55

这是因为sql如何对待INNOT IN查询。

对于列表中的每个元素,NOT IN计算结果为!=子句,您的列表(p列)包含NULL值。因此,value != NULL的计算结果是未知的。

复制:非IN子句和空值

试试这个:

代码语言:javascript
运行
复制
select n,
 case 
 when p is null then 'Root'
 when p is not null and (n in (select p from BST)) then 'Inner'
 when p is not null and (n not in (select p from BST where p IS NOT null)) then 'Leaf'
end
from BST order by n

这将产生预期的结果。

票数 5
EN

Stack Overflow用户

发布于 2018-05-10 05:14:49

下面是与NULL一起使用时not in行为的一个很好的示例

代码语言:javascript
运行
复制
select 
case 
  when NULL not in ('a','b') then 'not in'
  when NULL in ('a','b') then 'in'
  else 'What?' 
end

这将返回What?,这似乎是出乎意料的。

票数 1
EN

Stack Overflow用户

发布于 2018-05-10 11:55:45

学习如何将not exists与子查询一起使用,而不是not in。它具有正确的语义,因此您不太容易出错。

您可以将case表达式编写为:

代码语言:javascript
运行
复制
select n,
       (case when p is null then 'Root'
             when exists (select 1 from BST bst2 where bst2.p = bst.n)
             then 'Inner' 
             else 'Leaf'
        end)
from BST
order by n;

注意,我还简化了case表达式。您不需要重复这些条件,因为case表达式是按顺序计算的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50265704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档