我希望创建一个触发器。
这是我的两张桌子,
kk_settlements
表
| paidBy | paidTo | settlementAmount | createdAt | groupId |
kk_user_relations
表
| userId | userId_1 | groupId | amount |
现在当INSERT
上有kk_settlements
时,我想创建触发器和UPDATE
kk_user_relations
表。
在执行UPDATE
之前,我想检查paidBy
是否小于或大于paidTo
,并根据该内容查找kk_user_relations
表中的行是得到更新。 (由于kk_user_relations
中的所有行都由userId
< userId_1
我尝试添加以下trigger
(我正在使用phpmyadmin)
IF (paidBy < paidTo)
THEN
UPDATE kk_user_relations
SET kk_user_relations.amount = kk_user_relations.amount + settlementAmount
WHERE kk_user_relations.userId = paidBy
AND kk_user_relations.userId_1 = paidTo
AND kk_user_relations.groupId = groupId;
ELSE
UPDATE kk_user_relations
SET kk_user_relations.amount = kk_user_relations.amount + settlementAmount
WHERE kk_user_relations.userId_1 = paidBy
AND kk_user_relations.userId = paidTo
AND kk_user_relations.groupId = groupId;
END IF
此trigger
不起作用并抛出错误。
#1054 - Unknown column 'paidBy' in 'field list'
phpmyadmin生成的完整trigger
是
DROP TRIGGER IF EXISTS `kk_update_user_relations`;
CREATE DEFINER=`root`@`localhost` TRIGGER `kk_update_user_relations`
AFTER INSERT ON `kk_settlements`
FOR EACH ROW
IF (paidBy < paidTo) THEN
UPDATE kk_user_relations
SET kk_user_relations.amount = kk_user_relations.amount + settlementAmount
WHERE kk_user_relations.userId = paidBy
AND kk_user_relations.userId_1 = paidTo
AND kk_user_relations.groupId = groupId;
ELSE UPDATE kk_user_relations
SET kk_user_relations.amount = kk_user_relations.amount + settlementAmount
WHERE kk_user_relations.userId_1 = paidBy
AND kk_user_relations.userId = paidTo
AND kk_user_relations.groupId = groupId;
END IF
我哪里错了?我想在触发器中使用paidBy
和paidTo
时我出错了。请纠正我。
还建议是否有更好的方法来完成同样的事情。我愿意接受建议。
答案 0 :(得分:0)
尝试NEW.paidBy和NEW.paidTo。
这就是你如何引用FOR EACH ROW当前行的值。在UPDATE触发器中,您可以使用OLD和NEW来引用字段的先前值和要更改的字段。