Replace null with 0 in MySQL

2019-01-14 14:43发布

I am getting NULL values in the results of an operation in MySQL.

Is there a way to convert the NULL values into the value 0?

标签: mysql sql null
5条回答
Anthone
2楼-- · 2019-01-14 15:18

Yes, by using COALESCE.

SELECT COALESCE(null_column, 0) AS null_column FROM whatever;

COALESCE goes through the list of values you give it, and returns the first non-null value.

查看更多
干净又极端
3楼-- · 2019-01-14 15:23

If you messed up and have NULLs in existing table layout and want zeros, here is solution:

UPDATE `table` SET `somefield`=0 WHERE `somefield` is null
查看更多
SAY GOODBYE
4楼-- · 2019-01-14 15:30

There is the COALESCE method which return the first non-null parameter, in your case :

COALESCE(field, 0)

But you can use this if you want more :

COALESCE(field1, field2, 0)
查看更多
我只想做你的唯一
5楼-- · 2019-01-14 15:38

I am adding this answer because no one mentioned IFNULL function

You can use IFNULL

SELECT IFNULL(column_name, 0) FROM table_name;

IFNULL will return column's value (if it has something other than NULL) otherwise second parameter passed (in this case 0).

查看更多
家丑人穷心不美
6楼-- · 2019-01-14 15:42

MySQL:

SELECT COALESCE(Mycolumn, 0);
查看更多
登录 后发表回答