mysql

时间:2017-10-06 13:12:20

标签: mysql

目前我为我的下一个项目构建了数据库,但我的数据库包括讨论,帖子和其他一些表

讨论表

id | user_id | title | comments_count | replies_count

帖子表

id | user_id | content | type
帖子表中的

类型可能是评论,讨论回复 我希望在讨论表中的comments_count列是自动引用并自动选择具有类型注释的帖子的数量,我想为replies_count提供相同的内容。

如果无法做到这一点,可以帮助我自动更新评论并使用触发器或事件自动回复计数列

我希望你能帮助我

谢谢:)

1 个答案:

答案 0 :(得分:1)

[EDITED]

假设你有这个架构:

CREATE TABLE discussions(id INT,user_id INT, title VARCHAR(50), comments_count INT, replies_count INT);
CREATE TABLE posts(id INT,user_id INT, content VARCHAR(50), type VARCHAR(50));

和表中的数据如:

INSERT INTO discussions VALUES
(1,1,"test1",0,0),
(2,2,"test2",0,0);

此触发器可能会发挥您想要的技巧

DELIMITER $

CREATE TRIGGER update_comments_count_trigger
AFTER INSERT ON posts
FOR EACH ROW
BEGIN
  UPDATE discussions d 
  SET d.comments_count = (SELECT count(*) from posts where user_id = NEW.user_id and type="comment");

  UPDATE discussions d 
  SET d.replies_count = (SELECT count(*) from posts where user_id = NEW.user_id and type="reply");


END

因此,当您向帖子表插入值时,如:

INSERT INTO posts VALUES 
(1,1,'content1','comment'),
(1,2,'content2','comment'),
(1,2,'reply1','reply');

应更新comments_count和replies_count。

相关问题