【问题标题】:MySQL Trigger: update record in one table where record in the same row match select queryMySQL触发器:更新一张表中的记录,其中同一行中的记录匹配选择查询
【发布时间】:2020-05-02 11:21:49
【问题描述】:

对 MySQL 和数据库不熟悉,需要一些帮助。 我有桌子:

约会

  • appointment_id int PK ,
  • patient_id int ,
  • 医生 ID 整数,
  • appointment_time 日期时间。

队列

  • appointment_id int PK,
  • actual_time 日期时间。

queue_summary

  • 日期日期时间,
  • doctor_id int PK ,
  • num_of_patients int。

我需要编写一个触发器来更新 num_of_patients,方法是在 queue_summary 中的医生 ID 与插入到 queue 中与预约对应的新行重叠的行中的记录中添加 +1(提取医生 ID)。

例如。如果插入到queue:

约会表状态:

需要更新:

我编写了以下选择查询来提取受插入/删除影响的医生id到队列:

 select appointment.doctor_id
            from appointment as a 
            join queue as q 
            on a.appointment_id = q.appointment_id
            where new.appointment_id = a.appointment_id;

我尝试按如下方式编写触发器:

delimiter // 

CREATE TRIGGER tr_insert 
    BEFORE INSERT ON queue
    FOR EACH ROW
        BEGIN

          set queue_summary.num_of_patients = queue_summary.num_of_patients+1
          where queue_summary.doctor_id = (
          select appointment.doctor_id
            from appointment as a 
            join queue as q 
            on a.appointment_id = q.appointment_id
            where new.appointment_id = a.appointment_id
        )
       END;//
 delimiter ;

但是没有运气... 我知道我在 where 部分有一些语法错误,但我无法让它工作...... 请指教, 提前致谢!

【问题讨论】:

    标签: mysql sql mysql-workbench


    【解决方案1】:

    触发器中的 SET 命令只能用于 NEW var,它指向正在处理的行。要更新另一个表,您需要发出普通的 UPDATE 命令:

    delimiter // 
    
    CREATE TRIGGER tr_insert 
        BEFORE INSERT ON queue
        FOR EACH ROW
            BEGIN
    
              update queue_summary
              set queue_summary.num_of_patients = queue_summary.num_of_patients+1
              where queue_summary.doctor_id = (
              select appointment.doctor_id
                from appointment as a 
                join queue as q 
                on a.appointment_id = q.appointment_id
                where new.appointment_id = a.appointment_id
            )
           END;//
     delimiter ;
    

    这就是为什么在 where 出现语法错误的原因,这是因为 mysql set 命令不会期望它在那里,SET 只接受 var name 和 value。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      相关资源
      最近更新 更多