2010-10-31 12 views
18

Wie kann ich etwas, das NULL zurückgibt, auf 0 umwandeln? Wenn das meine Frage ist: select col from table; wäre dies der richtige Weg, es zu tun: select cast(col as unsigned integer) from table;?MySQL Cast NULL zu Ganzzahl 0

Vielen Dank.

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

COALESCE() Gibt den ersten Nicht-NULL Wert in der Liste oder NULL, wenn es keine nicht-NULL Werte sind:

Antwort

40

Sie würden vermutlich die COALESCE() Funktion verwenden möchten.

Testfall:

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

Ergebnis:

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

IFNULL(expr1, expr2) gibt den ersten Ausdruck, wenn es nicht null ist, sonst kehrt:

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

Danke, Daniel! – Francisc

2

Sie auch die IFNULL() Funktion nutzen zu können der zweite Ausdruck.

Testfall:

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

Ergebnis:

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