sql 触发器确保约会之间 30 天不起作用

sql Trigger ensuring 30 days between appointments not working

尝试创建触发器以确保约会之间至少间隔 30 天,但这似乎不起作用:

delimiter //
create trigger time_between_doses
before insert on appointment
for each row
begin 
if datediff((select appointment_time from appointment where new.patientSSN = patientSSN), 
new.appointment_time) < 30
    THEN SIGNAL SQLSTATE '45000'
    SET MYSQL_ERRNO = 9996,
    MESSAGE_TEXT = 'Not 30 days between appointments for this patient';
end if;
end //
delimiter ;

您要检查的查询将使用 exists。 “30 天”的含义并非 100% 清楚。想必您想知道 returns 是否有任何行:

select a.*
from appointment a
where new.patientSSN = a.patientSSN and
      new.appointment_time < a.appointment_time + interval 30 day;

不清楚的一件事是 30 天的限制是否适用于过去和未来。以及它是仅适用于过去的约会还是也适用于未来的约会。

您的版本是一个等待发生的错误,因为您正在使用需要单个值的子查询。如果子查询 returns 多行,那么代码会产生错误。上面的逻辑应该和exists.

一起使用