我写过一个触发器,每次为病人开处方时,都会将记录插入发票表中。触发器插入发票表的行使用处方表中的外键。但是我收到了错误:
无法添加或更新子行:外键约束失败(test
。invoice
,CONSTRAINT PrescriptionID
FOREIGN KEY(PrescriptionID
)
因此,尽管触发时间为'AFTER INSERT',但由于记录尚不存在,我的关系失败了。
有没有办法绕过这个或者我错过了什么?
CREATE DEFINER = CURRENT_USER TRIGGER `test`.`prescription_AFTER_INSERT`
AFTER INSERT ON `prescription`
FOR EACH ROW begin
INSERT INTO invoice (PrescriptionID, AmountDue)
SELECT pr.PrescriptionID, CASE
WHEN pa.PrescriptionCodeID = 'FF' THEN '0'
WHEN pa.PrescriptionCodeID = 'MM' THEN '8'
END
FROM prescription AS pr
JOIN patients AS pa
ON pa.PatientID = pr.PatientID
WHERE pr.prescriptionID = NEW.prescriptionID;
END