2010-10-31 20 views
18

¿Cómo puedo convertir algo que devuelve NULL a 0?MySQL Cast NULL en entero 0

Si esta es mi consulta: select col from table; ¿Esta sería la manera correcta de hacerlo: select cast(col as unsigned integer) from table;?

Gracias.

Respuesta

40

Usted probablemente querrá utilizar la función COALESCE():

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

COALESCE() devuelve el primer valor no NULL en la lista, o NULL si no hay valores no NULL.

caso

prueba:

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); 

Resultado:

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

Gracias, Daniel! – Francisc

2

también puede utilizar la función de IFNULL():

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

IFNULL(expr1, expr2) devuelve la primera expresión si no es nulo, declaraciones de otra persona la segunda expresión caso

prueba:

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); 

Resultado:

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