【问题标题】:coalesce in SQL [duplicate]SQL中的合并[重复]
【发布时间】:2014-11-14 22:22:22
【问题描述】:

我在表格中有一个名为Indicator 的列。它包含YNNULL,或者只是空白。

下面两个逻辑是做什么的?

coalesce(Indicator, 'N') = 'N'
coalesce(Indicator, 'N') = 'Y'

似乎不仅仅返回Indicator 等于NY 的行。还有其他事情吗?

【问题讨论】:

    标签: mysql sql sql-server


    【解决方案1】:

    每种情况都有不同的答案

    对于

    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
    

    【讨论】:

      【解决方案2】:

      逻辑做了两件事。在功能上,第一个表达式等价于:

      (Indicator = 'N' or Indicator is null)
      

      此外,它还阻止在indicator 上使用索引(在大多数数据库中)。

      对于二元指标,指数的使用通常是次要的。此外,SQL 优化器在为or 条件使用索引方面非常糟糕。而且,当列是函数的参数时,它们几乎从不使用它们。

      【讨论】:

        【解决方案3】:

        coalesce(Indicator, 'N') 表示如果Indicator is null 则将N 作为它的值,否则为Indicator 持有的值。

        所以,如果 Indicator is null 则以下条件成立 TRUE

        coalesce(Indicator, 'N') = 'N'
        

        【讨论】:

          猜你喜欢
          • 2014-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多