首页 文章资讯内容详情

当MySQL中的记录为NULL时,在新列中返回0?

2026-06-04 1 花语

为此,您可以使用CASE语句。让我们首先创建一个表-

create table DemoTable703 (Price int);

使用插入命令在表中插入一些记录-

insert into DemoTable703 values(102); insert into DemoTable703 values(null); insert into DemoTable703 values(0); insert into DemoTable703 values(500); insert into DemoTable703 values(100); insert into DemoTable703 values(null); insert into DemoTable703 values(2340);

使用select语句显示表中的所有记录-

select *from DemoTable703;

这将产生以下输出-

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

使用CASE语句-

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)