mysql - 尝试在 MySQL 触发器中创建 DECIMAL(1,1)

标签 mysql sql triggers decimal

我编写了一个 MySQL 触发器,它在插入新评论时更新产品的平均评分。但是,当插入时抛出以下数据库异常 Numeric value out of range

值进入的列被设置为 DECIMAL(1,1)

我已经设置了以下触发器,但仍然出现错误。

CREATE TRIGGER `update_products_average_rating` AFTER INSERT ON  `reviews` 
FOR EACH ROW UPDATE products 
    SET average_rating = ( SELECT CAST( AVG( rating ) AS DECIMAL( 1, 1 ) ) 
    FROM reviews
    WHERE product_id = products.id ) 
WHERE id = NEW.product_id;

我希望 AS DECIMAL(1,1) 能解决问题,但事实并非如此。

我正在使用 MySQL 5.5。

最佳答案

“数值超出范围”表示数字对于分配给它的位置来说太大了。 DECIMAL(1,1) 是一个很小的分配,因此不足为奇。

来自documentation :

In a DECIMAL column declaration, the precision and scale can be (and usually is) specified; for example:

salary DECIMAL(5,2)

In this example, 5 is the precision and 2 is the scale. The precision represents the number of significant digits that are stored for values, and the scale represents the number of digits that can be stored following the decimal point.

Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99.

从这里可以看出,DECIMAL(1,1) 意味着您只能存储一个数字。如果您尝试存储一个以上的数字,那么对于那个位置来说就太大了。

编辑

要得到 3.5,您需要 DECIMAL (2, 1)。那是因为 3.5 有两位数字和一位小数。

关于mysql - 尝试在 MySQL 触发器中创建 DECIMAL(1,1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500918/

相关文章:

mysql - 如何排除总票数小于1的帖子?

postgresql - PostgreSQL 中的递归 BEFORE UPDATE 触发器不使用最后返回的新

postgresql - 将 UNIQUE 约束转换为 CHECK 或触发器

mysql - 检查两列mysql之间的多个值

mysql - SQLSTATE[HY000] [1045] 拒绝用户 'root' @'localhost' 的访问(使用密码 : NO)

.net - 如何以编程方式修改连接字符串?

MySQL触发器更新最后插入的行

php - 如何检查php中的变量是否为空以及是否不需要在表中显示

sql - psycopg2: (col1, col2) IN my_list: ProgrammingError: "ARRAY"处或附近的语法错误

sql - 需要对以下数据和条件进行 SQL 查询