在UPDATE

时间:2016-01-14 00:35:40

标签: mysql phpmyadmin

我希望创建一个触发器。

这是我的两张桌子,

  1. kk_settlements

    | paidBy | paidTo | settlementAmount | createdAt | groupId |
    
  2. kk_user_relations

    | userId | userId_1 | groupId | amount |
    
  3. 现在当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 
    

    我哪里错了?我想在触发器中使用paidBypaidTo时我出错了。请纠正我。

    还建议是否有更好的方法来完成同样的事情。我愿意接受建议。

1 个答案:

答案 0 :(得分:0)

尝试NEW.paidBy和NEW.paidTo。

这就是你如何引用FOR EACH ROW当前行的值。在UPDATE触发器中,您可以使用OLD和NEW来引用字段的先前值和要更改的字段。