我有一个具有这种结构的数据库:
如何更新user_status ='已删除'自动设置:
question_status = deleted
answer_status = deleted
like_status = deleted
答案 0 :(得分:1)
假设您正在使用SQL服务器(因为我看不到指定的数据库),我会说对表用户执行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
然后在表格之后再添加两个表格答案和喜欢的更新(抱歉,无论如何我会猜测连接),用分号分隔,它应该可以工作。
更多关于sql server中的触发器 - https://msdn.microsoft.com/en-us/library/ms189799.aspx
答案 1 :(得分:1)
这个触发器有什么作用?
代码:
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 ;
您稍后可能会注意到的可能流程
只需在您的网站上考虑这种情况,QuestionA已被删除&#39;一些主持人,现在当用户(这个问题的海报)被重新激活时,所有这些主持的问题/答案都会回来!
理想情况下,您应该有另一种状态来决定是自动删除还是手动删除。也许&#39; auto_delete&#39;并且&#39;删除&#39;而不只是使用&#39;删除&#39;。
答案 2 :(得分:1)
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应该解决流程