有两个表:'回复'和'帖子',此触发器放在'回复'表中。
每次在回复表中放置一个新条目时,触发器会检查post表上一行中值是否为某些条件,且匹配的ID为新条目。
这是我到目前为止所做的:
CREATE TABLE posts(
p_Id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
p_Health INT UNSIGNED NOT NULL DEFAULT 0,
p_Bump INT UNSIGNED NOT NULL DEFAULT 0,
p_Time TIMESTAMP);
CREATE TABLE replies(
r_Id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
r_To INT UNSIGNED NOT NULL,
r_Time TIMESTAMP);
CREATE TRIGGER bump AFTER INSERT ON replies
FOR EACH ROW
BEGIN
IF posts.p_Bump < 5 WHERE posts.p_Id = NEW.r_To AND (SELECT COUNT(r_To) FROM replies WHERE r_To = NEW.r_To)%10 = 10 THEN
UPDATE posts
SET posts.p_Bump = posts.p_Bump + 1 AND
SET posts.p_Health = 0 WHERE posts.p_Id = NEW.r_To;
END IF;
END;
INSERT INTO posts() VALUES();
INSERT INTO replies(r_To) VALUES(1);
INSERT INTO replies(r_To) VALUES(1);
INSERT INTO posts() VALUES();
INSERT INTO replies(r_To) VALUES(2);
INSERT INTO replies(r_To) VALUES(2);
INSERT INTO replies(r_To) VALUES(2);
'r_To'是“回复”的简写,它存储了回复所针对的帖子的ID。
SQLFiddle说第4行有一个错误,我尝试用SELECT COUNT(r_To)
进行算术运算,模数为10。
无法创建SQLFiddle,如果它不正确,它不会保存我的架构。
答案 0 :(得分:1)
这里有两个问题!首先,您需要更改分隔符以定义触发器。
DELIMITER $$
CREATE TRIGGER bump AFTER INSERT ON replies
FOR EACH ROW
BEGIN
IF posts.p_Bump < 5 WHERE posts.p_Id = NEW.r_To AND (SELECT COUNT(r_To) FROM replies WHERE r_To = NEW.r_To)%10 = 10 THEN
UPDATE posts
SET posts.p_Bump = posts.p_Bump + 1 AND
SET posts.p_Health = 0 WHERE posts.p_Id = NEW.r_To;
END IF;
END;
DELIMITER ;
第二个是sqlfiddle.com不支持delimiter命令,所以你不能用这种方式创建一个小提琴。我不知道sqlfiddle的工作,但在控制台中键入它应该可以解决问题。
不确定这是否合法
IF posts.p_Bump < 5 WHERE posts.p_Id = NEW.r_To AND (SELECT COUNT(r_To) FROM replies WHERE r_To = NEW.r_To)%10 = 10 THEN
我认为你必须这样做
SELECT COUNT(r_To) into @myvar FROM replies WHERE r_To = NEW.r_To;
IF @myvar %10 = 10 THEN
UPDATE posts
SET posts.p_Bump = posts.p_Bump + 1 AND
SET posts.p_Health = 0 WHERE posts.p_Bump < 5 AND posts.p_Id = NEW.r_To;
END IF;
这是一个更简单的查询,我认为它符合您的期望。但是someint % 10
永远不会是10,它只能取0到9的值,所以你必须为此提出正确的条件。
答案 1 :(得分:1)
我认为模数应该在子选择
中完成BEGIN
IF posts.p_Bump < 5
WHERE posts.p_Id = NEW.r_To
AND (SELECT COUNT(r_To)%10
FROM replies WHERE r_To = NEW.r_To) = 10 THEN
UPDATE posts
SET posts.p_Bump = posts.p_Bump + 1 AND
SET posts.p_Health = 0 WHERE posts.p_Id = NEW.r_To;
END IF;
END;