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 次观看

开启您的 事业

通过完成课程获得认证

开始
广告