在 MySQL 中用 0 替换 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3532776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace null with 0 in MySQL
提问by NullVoxPopuli
I am getting NULL
values in the results of an operation in MySQL.
我NULL
在 MySQL 中的操作结果中获取值。
Is there a way to convert the NULL
values into the value 0?
有没有办法将NULL
值转换为值 0?
回答by Teekin
Yes, by using COALESCE
.
是的,通过使用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.
COALESCE 遍历您给它的值列表,并返回第一个非空值。
回答by Arif
I am adding this answer because no one mentioned IFNULL
function
我添加这个答案是因为没有人提到IFNULL
功能
You can use IFNULL
您可以使用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
).
IFNULL
将返回列的值(如果它有其他值NULL
),否则会传递第二个参数(在本例中为0
)。
回答by Alex Khimich
If you messed up and have NULLs in existing table layout and want zeros, here is solution:
如果您搞砸了现有表格布局中的 NULL 并想要零,这里是解决方案:
UPDATE `table` SET `somefield`=0 WHERE `somefield` is null
回答by Colin Hebert
There is the COALESCE
method which return the first non-null parameter, in your case :
COALESCE
在您的情况下,有返回第一个非空参数的方法:
COALESCE(field, 0)
But you can use this if you want more :
但是如果你想要更多,你可以使用它:
COALESCE(field1, field2, 0)
回答by Sjoerd
MySQL:
MySQL:
SELECT COALESCE(Mycolumn, 0);
回答by Alireza Saffar
you can put the 0 value into your insert input method by casting it:(int)0
您可以通过强制转换将 0 值放入您的插入输入法中:(int)0