数据库多表触发器

Database multiple tables trigger

我有一个具有这种结构的数据库:

更新user_status='deleted'时如何触发自动设置:

question_status = deleted
answer_status = deleted
like_status = deleted

假设您正在使用 SQL 服务器(因为我没有看到指定的数据库)我会说对 table 用户执行 1 个触发器如下(可能不准确)

CREATE TRIGGER [user_statusDeleted]
ON [users]
After UPDATE, INSERT --INSERT may not be relevant
AS 
BEGIN
UPDATE q
SET q.[question_status] = deleted
FROM [inserted] i 
    JOIN [questions] q
        ON i.[Id] = q.[asker_id] --or asked_id ?
        AND i.[user_status] = deleted

然后在这个之后为 table 的回答和点赞添加两个更新(抱歉,无论如何我都会猜测连接),用分号分隔,它应该可以工作。

更多关于 sql 服务器中触发器的信息 - https://msdn.microsoft.com/en-us/library/ms189799.aspx

这个触发器有什么作用?

  • 列表项
  • 定义新触发器
  • 检查 user_status 列是否已更新。
  • 检查 user_status 是否更新为 'deleted'
  • 获取该用户的 ID,并将其所有问题、答案和喜欢的状态更改为 'deleted'。

代码:

DELIMITER //
CREATE TRIGGER  user_delete BEFORE UPDATE ON users FOR EACH ROW
BEGIN
    IF NEW.user_status <> OLD.user_status
    THEN 
        IF STRCMP('deleted',NEW.user_status) = 0 THEN
            UPDATE question_status SET question_status = 'deleted' WHERE asker_id = NEW.id;
            UPDATE answers SET answer_status = 'deleted' WHERE who_answer_id = NEW.id;
            UPDATE likes SET like_status = 'deleted' WHERE liker_id = NEW.id;
        END IF;
        IF STRCMP('active',NEW.user_status) = 0 THEN
            UPDATE question_status SET question_status = 'active' WHERE asker_id = NEW.id;
            UPDATE answers SET answer_status = 'active' WHERE who_answer_id = NEW.id;
            UPDATE likes SET like_status = 'active' WHERE liker_id = NEW.id;
        END IF;
    END IF;
END//
DELIMITER ;

您稍后可能会注意到的可能流程

考虑一下您网站上的这种情况,问题 A 已经被某些版主 'deleted',现在当用户(该问题的发帖人)被重新激活时,所有这些版主 questions/answers 都会回来吧!

理想情况下,您应该有另一个状态来决定它是自动删除还是手动删除。也许 'auto_delete' 和 'delete' 而不是仅仅使用 'delete'.

BEGIN
    IF NEW.user_status <> OLD.user_status
    THEN 
        IF STRCMP('deleted',NEW.user_status) = 0 THEN
            UPDATE questions SET question_status = 'deleted' WHERE asker_id = NEW.id AND question_status != 'mod_deleted';
            UPDATE answers SET answer_status = 'deleted' WHERE commentator_id = NEW.id AND answer_status != 'mod_deleted';
            UPDATE likes SET like_status = 'deleted' WHERE liker_id = NEW.id AND like_status != 'mod_deleted';
        END IF;
        IF STRCMP('active',NEW.user_status) = 0 THEN
            UPDATE questions SET question_status = 'active' WHERE asker_id = NEW.id AND question_status != 'mod_deleted';
            UPDATE answers SET answer_status = 'active' WHERE commentator_id = NEW.id AND answer_status != 'mod_deleted';
            UPDATE likes SET like_status = 'active' WHERE liker_id = NEW.id AND like_status != 'mod_deleted';
        END IF;
    END IF;
END

_status 字段是枚举类型,所以如果我添加 mod_deleted 并在更新中添加一个 AND 应该解决流程