MySQL Trigger - update table with value selected f

2019-05-31 02:53发布

I'm having problems updating row in a table with value selected from another table in MySQL Trigger. My Trigger looks like this

CREATE TRIGGER update_user_last_login
    AFTER INSERT or UPDATE ON last FOR EACH ROW
    BEGIN 
        DECLARE _user_id INTEGER;
        SELECT user_id INTO _user_id FROM user_profile WHERE user_name = NEW.username;
        UPDATE user set last_login = NEW.seconds WHERE id = _user_id;
    END 

I'm getting error message:

ERROR 1054 (42S22): Unknown column '_user_id' in 'where clause'

Could somebody point me to the right direction please?

Thank you very much, Milan.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-31 03:14

Try as bellow

UPDATE user set last_login = NEW.seconds WHERE id = :_user_id;
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-31 03:19

You could cut out the intermediate variable like this...

UPDATE user
    SET last_login = NEW.seconds
    WHERE id = (SELECT user_id
                    FROM user_profile
                    WHERE user_name = NEW.username);
查看更多
唯我独甜
4楼-- · 2019-05-31 03:23

This is a syntax error on the compound trigger event (INSERT or UPDATE). Try:

CREATE TRIGGER update_user_last_login
    AFTER UPDATE ON last FOR EACH ROW ...

I don't think mysql supports compound events in the same trigger. You could create two triggers, one for after insert and one for after update. Those two triggers can call the same code in duplicate or call a common stored procedure.

查看更多
登录 后发表回答