2015-07-20 42 views

回答

2

在您的最后一个例子MySQL会尝试将VARCHARCAST成数值。当您尝试将非数字字符串转换为,例如,DECIMAL转换将首先停止为非数字字符。空字符串会匹配0

例如:

> select cast('x123' as decimal); 
+-------------------------+ 
| cast('x123' as decimal) | 
+-------------------------+ 
|      0 | 
+-------------------------+ 
1 row in set, 1 warning (0.00 sec) 

> show warnings; 
+---------+------+-------------------------------------------+ 
| Level | Code | Message         | 
+---------+------+-------------------------------------------+ 
| Warning | 1292 | Truncated incorrect DECIMAL value: 'x123' | 
+---------+------+-------------------------------------------+ 

在另一方面,如果你拥有领先的数字字符的将被转换为十进制:

> select cast('123x' as decimal); 
+-------------------------+ 
| cast('123x' as decimal) | 
+-------------------------+ 
|      123 | 
+-------------------------+ 
1 row in set (0.00 sec) 

在这种情况下非数字尾随字符将被默默忽略。转换为INTEGER将以相似的方式进行,结果相同。更多细节可以从manual找到。