MySQL 中 record 為 NULL 時,在新的列中返回 0?


為此,您可以使用 CASE 語句。我們首先建立一個表 -

mysql> create table DemoTable703 (Price int);
Query OK, 0 rows affected (0.46 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable703 values(102);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable703 values(null);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable703 values(0);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable703 values(500);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable703 values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable703 values(null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable703 values(2340);
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable703;

這將產生以下輸出 -

+-------+
| Price |
+-------+
| 102   |
| NULL  |
| 0     |
| 500   |
| 100   |
| NULL  |
| 2340  |
+-------+
7 rows in set (0.00 sec)

使用 CASE 語句 -

mysql> select Price, case When Price IS NULL Then 0 else Price END AS Result from DemoTable703;

這將產生以下輸出 -

+-------+--------+
| Price | Result |
+-------+--------+
| 102   | 102    |
| NULL  | 0      |
| 0     | 0      |
| 500   | 500    |
| 100   | 100    |
| NULL  | 0      |
| 2340  | 2340   |
+-------+--------+
7 rows in set (0.00 sec)

更新於: 21-Aug-2019

185 次觀看

開啟您的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.