在 MySQL 中將 NULL 型別轉換為 0


藉助 IFNULL() 函式,可以將 NULL 型別轉換為 0。語法如下 −

select ifnull(yourColumnName) as anyVariableName from yourTableName;

為了理解上述概念,我們首先建立一個表 −

mysql> create table TypecastDemo
   −> (
      −> AccountNumber int
   −> );
Query OK, 0 rows affected (0.84 sec)

我們插入一些具有 NULL 值的記錄。插入記錄的查詢如下 −

mysql> insert into TypecastDemo values(NULL);
Query OK, 1 row affected (0.13 sec)

mysql> insert into TypecastDemo values(1234);
Query OK, 1 row affected (0.14 sec)

mysql> insert into TypecastDemo values(9876);
Query OK, 1 row affected (0.14 sec)

mysql> insert into TypecastDemo values(6666);
Query OK, 1 row affected (0.16 sec)

mysql> insert into TypecastDemo values(NULL);
Query OK, 1 row affected (0.27 sec)

mysql> insert into TypecastDemo values(NULL);
Query OK, 1 row affected (0.36 sec)

mysql> insert into TypecastDemo values(3214);
Query OK, 1 row affected (0.34 sec)

現在,可以使用 select 語句顯示所有記錄。查詢如下 −

mysql> select *from TypecastDemo;

以下為輸出 −

+---------------+
| AccountNumber |
+---------------+
|          NULL |
|          1234 |
|          9876 |
|          6666 |
|          NULL |
|          NULL |
|          3214 |
 +---------------+
7 rows in set (0.00 sec)

應用我們上面看到的語法將 NULL 型別轉換為 0。查詢如下 −

mysql> select ifnull(AccountNumber,0) as TypeCastNullToZero from TypecastDemo;

以下為輸出 −

+--------------------+
| TypeCastNullToZero |
+--------------------+
|                  0 |
|               1234 |
|               9876 |
|               6666 |
|                  0 |
|                  0 |
|               3214 |
+--------------------+
7 rows in set (0.00 sec)

如果您需要多列,可以使用 COALESCE。

更新於:2020-6-25

408 次瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告