【问题标题】:Trigger to insert percentage value in a table based on the values of two different fields触发器根据两个不同字段的值在表中插入百分比值
【发布时间】:2011-06-20 11:49:46
【问题描述】:

我有一个表 'attendance' 有 3 个字段 'class_total'、'class_attended' 和 'attendance_percent'。 每当在字段“class_total”和“class_attended”中插入/更新值时,我想插入/更新“attendance_percent”的值(class_attended/class_total)*100。 为此,我使用了触发器:

CREATE TRIGGER percent_update
BEFORE INSERT ON attendance
FOR EACH ROW
SET NEW.attendance_percent =(attendance.class_attended/attendance.class_total)*100 ;

但它不起作用。

【问题讨论】:

  • 如果从其他字段计算出出席百分比,您可以在 SELECT 语句中即时计算该值。
  • 您能详细说明“不工作”吗?您是否收到错误、未插入数据、插入错误数据等?示例帮助:)
  • 触发器查询没问题。但是之后当我尝试在表中插入值时:INSERT INTO admission(class_total,class_attended) VALUES(5,4); Mysql 给出错误 1109(42S02):Unknown table 'attendance' in field list。如果我删除触发器出席更新,插入查询工作正常。
  • 为什么要使用触发器来做到这一点?鉴于百分比始终是出勤率/总数,为什么不将百分比作为计算列(并消除触发器的复杂性)?

标签: mysql sql triggers


【解决方案1】:

使用 NEW 子句代替表名 -

...
SET NEW.attendance_percent = (NEW.class_attended/NEW.class_total)
...

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2016-10-03
    相关资源
    最近更新 更多