开发者

MySQL Trigger - update table with value selected from another table

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 poin开发者_Go百科t me to the right direction please?

Thank you very much, Milan.


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.


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);


Try as bellow

UPDATE user set last_login = NEW.seconds WHERE id = :_user_id;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜