2014-11-14 19 views
2

我在表中有一個名爲Indicator的列。它包含Y,N,NULL,或只是空白。SQL中的合併

以下兩個邏輯是做什麼的?

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

似乎不只是返回行,其中Indicator等於NY。還有其他事情嗎?

回答

2

對於每個條件有不同的答案

對於

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 
0

邏輯做兩件事。在功能上,第一個表達式是等效於:

(Indicator = 'N' or Indicator is null) 

此外,它也可以防止索引,從上indicator被使用(在大多數數據庫)。

對於二元指示符,索引的使用通常不重要。另外,SQL優化器在使用or條件的索引時相當糟糕。而且,當列是函數的參數時,它們幾乎從不使用它們。

0

coalesce(Indicator, 'N')說如果Indicator is null則取N,因爲它的值其他值爲Indicator

所以,如果Indicator is null那麼以下條件成立TRUE

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