MySQL十进制字段'数据在第1行的第x列被截断'问题

yc.*_*yc. 5 mysql sql decimal

我有一个带小数(16,2)字段的mysql表.看起来像使用另一个十进制(16,2)字段字符串的加法操作可能会导致Data truncated for column x at row 1问题,这会在我的django项目中引发异常.

我知道该字段的乘法或除法运算会导致此问题,因为结果可能不适合十进制(16,2)定义,但加法和减法操作是否相同?

我的MySQL服务器版本是5.5.37-0ubuntu0.14.04.1.您可以从下面重现此问题:

mysql> drop database test;
Query OK, 1 row affected (0.10 sec)

mysql> create database test;
Query OK, 1 row affected (0.00 sec)

mysql> use test;
Database changed
mysql> create table t(price decimal(16,2));
Query OK, 0 rows affected (0.16 sec)

mysql> insert into t values('2004.74');
Query OK, 1 row affected (0.03 sec)

mysql> select * from t;
+---------+
| price   |
+---------+
| 2004.74 |
+---------+
1 row in set (0.00 sec)

mysql> update t set price = price + '0.09';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update t set price = price + '0.09';
Query OK, 1 row affected, 1 warning (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> show warnings;
+-------+------+--------------------------------------------+
| Level | Code | Message                                    |
+-------+------+--------------------------------------------+
| Note  | 1265 | Data truncated for column 'price' at row 1 |
+-------+------+--------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from t;
+---------+
| price   |
+---------+
| 2004.92 |
+---------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

Iły*_*sov 8

有两个问题:

  1. 你没有存储十进制值,你正在尝试存储字符串/ varchar,它由mysql转换为double值,例如下面的代码不会给出错误update t set price = price + 0.09;(甚至执行几次)

  2. 无论如何,这段代码给出了预期的警告(注释编号),update t set price = price + 0.091;您可以将其更改update t set price = price + cast(0.091 as decimal(16,2));为当然使用强制转换,您也可以使用字符串值update t set price = price + cast('0.09' as decimal(16,2));