mysql空值函式 SQL NULL 函式

2021-10-20 23:26:25 字數 1241 閱讀 3449

sql isnull()、nvl()、ifnull() 和 coalesce() 函式

請看下面的 "products" 表:

p_id

productname

unitprice

unitsinstock

unitsonorder

computer

printer

telephone

假如 "unitsonorder" 是可選的,而且可以包含 null 值。

我們使用如下 select 語句:

select productname,unitprice*(unitsinstock+unitsonorder)

from products

在上面的例子中,如果有 "unitsonorder" 值是 null,那麼結果是 null。

微軟的 isnull() 函式用於規定如何處理 null 值。

nvl(), ifnull() 和 coalesce() 函式也可以達到相同的結果。

在這裡,我們希望 null 值為 0。

下面,如果 "unitsonorder" 是 null,則不利於計算,因此如果值是 null 則 isnull() 返回 0。

sql server / ms access

select productname,unitprice*(unitsinstock+isnull(unitsonorder,0))

from products

oracle

oracle 沒有 isnull() 函式。不過,我們可以使用 nvl() 函式達到相同的結果:

select productname,unitprice*(unitsinstock+nvl(unitsonorder,0))

from products

mysql

mysql 也擁有類似 isnull() 的函式。不過它的工作方式與微軟的 isnull() 函式有點不同。

在 mysql 中,我們可以使用 ifnull() 函式,就像這樣:

select productname,unitprice*(unitsinstock+ifnull(unitsonorder,0))

from products

或者我們可以使用 coalesce() 函式,就像這樣:

select productname,unitprice*(unitsinstock+coalesce(unitsonorder,0))

from products

mysql中的ifnull 函式判斷空值

我們知道,在不同的資料庫引擎中,內建函式的實現 命名都是存在差異的,如果經常切換使用這幾個資料庫引擎的話,很容易會將這些函式弄混淆。比如說判斷空值的函式,在oracle中是nvl 函式 nvl2 函式,在sql server中是isnull 函式,這些函式都包含了當值為空值的時候將返回值替換成另乙個...

函式 COALESCE 函式處理空值

1.coalesce 函式介紹 這個函式主要用來進行空值處理,其引數格式如下 coalesce expression,value1,value2 valuen coalesce 函式的第乙個引數expression為待檢測的表示式,而其後的引數個數不定。coalesce 函式將會返回包括expres...

mysql 查詢判斷空值

select a.return car area,case when a.return car area then 0 else 1 end from t base bq branch a select a.return car area,case a.return car area when th...