我有一个varchar字段说值为174但是当我cast(field as decimal(3,1))
它给我总是99.9?我如何将其转换或转换为17.4?或者我必须在源级别更改要以十进制形式输入的输入吗?
答案 0 :(得分:3)
因为174
不能用小数点之前的2位和小数点之后的1位表示。 decimal(3,1)
表示"总共3位数,小数点后1位(3位数)。
mysql> select cast('174' as decimal(3,1));
+-----------------------------+
| cast('174' as decimal(3,1)) |
+-----------------------------+
| 99.9 |
+-----------------------------+
1 row in set, 1 warning (0.00 sec)
它会发出警告,可以显示:
mysql> show warnings;
+---------+------+----------------------------------------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------------------------------------+
| Warning | 1264 | Out of range value for column 'cast('174' as decimal(3,1))' at row 1 |
+---------+------+----------------------------------------------------------------------+
1 row in set (0.00 sec)
将数字除以10,然后重试:
mysql> select cast('174'/10 as decimal(3,1));
+--------------------------------+
| cast('174'/10 as decimal(3,1)) |
+--------------------------------+
| 17.4 |
+--------------------------------+
1 row in set (0.00 sec)