【问题标题】:Mysql update trigger only on specific idMysql更新仅在特定ID上触发
【发布时间】:2023-02-25 23:16:20
【问题描述】:

我有看起来像这样的表

commons_db.sites

user_id | active 
1       |    0   
2       |    1   

commons_db.users

site_id  | user_id | status
50       |    1    |   1
51       |    2    |   0

我想创建一个触发器,以便在我更新 active 列时更改 site_idstatus 列。到目前为止它看起来像这样。

UPDATE commons_db.users
SET `status` = ! NEW.active
WHERE user_id in (
    SELECT user_id FROM
        commons_db.sites
        INNER JOIN 
            (SELECT * FROM commons_db.users) AS users 
        using (user_id)
    );

它有效,但它也会更改其他 ID 的 status。我试图添加一行

AND OLD.active != NEW.active

但它什么也没做。我错过了什么?

【问题讨论】:

  • 是的,我希望 status 和 active 彼此相反。我没有对 user_id 进行任何更改。我只用它来连接触发器中我需要的两个表
  • 它给出了一个错误:错误 1054:“新”中的未知列“user_id”

标签: mysql triggers mysql-workbench


【解决方案1】:

Based on the tables in your example, this works fine for me:

DELIMITER //

CREATE TRIGGER tr_sites_after_update AFTER UPDATE ON sites
  FOR EACH ROW
  BEGIN
    IF NEW.active <> OLD.active THEN
      UPDATE users SET status = NOT NEW.active WHERE user_id = NEW.user_id;
    END IF;
  END;//

DELIMITER ;

Here's a db<>fiddle

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    相关资源
    最近更新 更多