MySQL 触发器 - 使用从另一个表中选择的值更新表

发布于 2024-09-16 11:57:33 字数 528 浏览 11 评论 0原文

我在使用从 MySQL 触发器中的另一个表中选择的值更新表中的行时遇到问题。我的触发器看起来像这样,

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 

我收到错误消息:

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

有人能给我指出正确的方向吗?

非常感谢, 米兰。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独夜无伴 2024-09-23 11:57:33

这是复合触发事件(INSERT 或 UPDATE)的语法错误。尝试:

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

我不认为 mysql 支持同一触发器中的复合事件。您可以创建两个触发器,一个用于插入后,一个用于更新后。这两个触发器可以重复调用相同的代码或调用公共存储过程。

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.

闻呓 2024-09-23 11:57:33

你可以像这样删除中间变量......

UPDATE user
    SET last_login = NEW.seconds
    WHERE id = (SELECT user_id
                    FROM user_profile
                    WHERE user_name = NEW.username);

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);
傲性难收 2024-09-23 11:57:33

尝试如下

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

Try as bellow

UPDATE user set last_login = NEW.seconds WHERE id = :_user_id;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文