1

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.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Milan
  • 11
  • 1
  • 1
  • 2
  • 2
    This is an oldie but just in case someone else runs into this. In MySQL if you reference what looks like a variable without surrounding it with '' mysql will treat it as a column. – ppetree Apr 19 '13 at 19:59

3 Answers3

1

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.

zevra0
  • 271
  • 1
  • 5
0

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);
Brian Hooper
  • 21,544
  • 24
  • 88
  • 139
0

Try as bellow

UPDATE user set last_login = NEW.seconds WHERE id = :_user_id;
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Oct 07 '16 at 11:25