我在这个数据库中有多个表;其中两个涉及此触发器
create table shipment_item(
shipmentID int not null,
shipmentItemID int not null,
purchaseID int not null,
insuredValue decimal(5,2) not null,
constraint shipment_ItemPK primary key(shipmentID, shipmentItemID),
constraint shipmentFK foreign key(shipmentID)
references shipment(shipmentID)
on delete cascade,
constraint purchaseFK foreign key(purchaseID)
references purchase(purchaseID)
);
create table purchase(
purchaseID int not null auto_increment,
storeID int not null,
purchaseDate date not null,
description char(30) not null,
category char(30) not null,
price decimal(5,2) not null,
constraint purchasePK primary key(purchaseID),
constraint storeFK foreign key(storeID)
references store(storeID)
);
我正在尝试在MySQL数据库中实现触发器。该触发器看起来像这样
DELIMITER //
CREATE TRIGGER checkInsuranceTrigger
BEFORE INSERT ON shipment_item
FOR EACH ROW BEGIN
IF(shipment_item.insuredValue <= purchase.price) THEN
SET NEW.insuredValue = purchase.price;
END IF;
END
//
DELIMITER ;
当我实现此触发器然后尝试将数据插入到shipment_item表中时,我收到以下错误
错误代码1109:字段列表中的未知表'shipment_item'
答案 0 :(得分:0)
我可以建议验证该表是否与触发器本身存在在同一个数据库中?
答案 1 :(得分:0)
使用 NEW
关键字引用正在插入的行中的列,就像您在SET语句中所做的那样。
要引用其他表中的行的值,您需要一个SQL语句,在您的情况下,看起来像是想要一个SELECT。
例如(按照触发器中逻辑的概述),如下所示:
BEGIN
-- local variable
DECLARE ln_purchase_price DECIMAL(5,2);
-- populate local variable (this is just an example of one way to do this)
SELECT p.price
INTO ln_purchase_price
FROM purchase p
WHERE p.purchaseID = NEW.purchaseID
LIMIT 1;
-- compare value from row to local variable
IF (NEW.insuredValue <= ln_purchase_price) THEN
SET NEW.insuredValue = ln_purchase_price;
END IF;