【发布时间】:2014-11-14 22:22:22
【问题描述】:
我在表格中有一个名为Indicator 的列。它包含Y、N、NULL,或者只是空白。
下面两个逻辑是做什么的?
coalesce(Indicator, 'N') = 'N'
coalesce(Indicator, 'N') = 'Y'
似乎不仅仅返回Indicator 等于N 或Y 的行。还有其他事情吗?
【问题讨论】:
标签: mysql sql sql-server
我在表格中有一个名为Indicator 的列。它包含Y、N、NULL,或者只是空白。
下面两个逻辑是做什么的?
coalesce(Indicator, 'N') = 'N'
coalesce(Indicator, 'N') = 'Y'
似乎不仅仅返回Indicator 等于N 或Y 的行。还有其他事情吗?
【问题讨论】:
标签: mysql sql sql-server
每种情况都有不同的答案
对于
coalesce(Indicator, 'N') = 'N'
你得到
coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True
coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False
coalesce(Null, 'N') = 'N' --> 'N' = 'N' --> True
对于
coalesce(Indicator, 'N') = 'Y'
你得到
coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True
coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False
coalesce(Null, 'N') = 'Y' --> 'N' = 'Y' --> False
【讨论】:
逻辑做了两件事。在功能上,第一个表达式等价于:
(Indicator = 'N' or Indicator is null)
此外,它还阻止在indicator 上使用索引(在大多数数据库中)。
对于二元指标,指数的使用通常是次要的。此外,SQL 优化器在为or 条件使用索引方面非常糟糕。而且,当列是函数的参数时,它们几乎从不使用它们。
【讨论】:
coalesce(Indicator, 'N') 表示如果Indicator is null 则将N 作为它的值,否则为Indicator 持有的值。
所以,如果 Indicator is null 则以下条件成立 TRUE
coalesce(Indicator, 'N') = 'N'
【讨论】: