我在表中有一個名爲Indicator
的列。它包含Y
,N
,NULL
,或只是空白。SQL中的合併
以下兩個邏輯是做什麼的?
coalesce(Indicator, 'N') = 'N'
coalesce(Indicator, 'N') = 'Y'
似乎不只是返回行,其中Indicator
等於N
或Y
。還有其他事情嗎?
我在表中有一個名爲Indicator
的列。它包含Y
,N
,NULL
,或只是空白。SQL中的合併
以下兩個邏輯是做什麼的?
coalesce(Indicator, 'N') = 'N'
coalesce(Indicator, 'N') = 'Y'
似乎不只是返回行,其中Indicator
等於N
或Y
。還有其他事情嗎?
對於每個條件有不同的答案
對於
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'