在 MySQL 中使用 NULL 行乘以列?


要與 NULL 行相乘,可以使用 COALESCE()。讓我們首先建立一個表 −

mysql> create table DemoTable1842
     (
     NumberOfItems int,
     Amount int
     );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1842 values(10,40);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1842 values(20,5);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1842 values(NULL,10);
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select * from DemoTable1842;

這將產生以下輸出 −

+---------------+--------+
| NumberOfItems | Amount |
+---------------+--------+
|            10 |     40 |
|            20 |      5 |
|          NULL |     10 |
+---------------+--------+
3 rows in set (0.00 sec)

以下是要將列與 NULL 行相乘的查詢 −

mysql> select NumberOfItems,Amount,
     coalesce(NumberOfItems,1)*Amount as Total
     from DemoTable1842;

這將產生以下輸出 −

+---------------+--------+-------+
| NumberOfItems | Amount | Total |
+---------------+--------+-------+
|            10 |     40 |   400 |
|            20 |      5 |   100 |
|          NULL |     10 |    10 |
+---------------+--------+-------+
3 rows in set (0.00 sec)

更新於:2019-12-26

402 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.