2010-10-31 76 views
18

如何转换返回NULL为0的内容?MySQL将NULL转换为整数0

如果这是我的查询:select col from table;这是否是正确的方法:select cast(col as unsigned integer) from table;

谢谢。

回答

40

你可能想使用COALESCE()功能:在列表中

SELECT COALESCE(col, 0) FROM `table`; 

COALESCE()返回第一个非NULL值,或者NULL如果没有非NULL值。

测试用例:

CREATE TABLE `table` (id int, col int); 

INSERT INTO `table` VALUES (1, 100); 
INSERT INTO `table` VALUES (2, NULL); 
INSERT INTO `table` VALUES (3, 300); 
INSERT INTO `table` VALUES (4, NULL); 

结果:

+------------------+ 
| COALESCE(col, 0) | 
+------------------+ 
|    100 | 
|    0 | 
|    300 | 
|    0 | 
+------------------+ 
4 rows in set (0.00 sec) 
+0

谢谢,丹尼尔! – Francisc 2010-10-31 00:24:52

2

您还可以使用IFNULL()功能:

SELECT IFNULL(col, 0) FROM `table`; 

IFNULL(expr1, expr2)返回第一个表达式,如果它不为空,否则返回第二个表达。

测试用例:

CREATE TABLE `table` (id int, col int); 

INSERT INTO `table` VALUES (1, 100); 
INSERT INTO `table` VALUES (2, NULL); 
INSERT INTO `table` VALUES (3, 300); 
INSERT INTO `table` VALUES (4, NULL); 

结果:

+----------------+ 
| IFNULL(col, 0) | 
+----------------+ 
|   100 | 
|    0 | 
|   300 | 
|    0 | 
+----------------+ 
4 rows in set (0.00 sec)