drop database if exists test;
create database test;
use test;
drop table if exists user;
CREATE TABLE user (
id INT AUTO_INCREMENT PRIMARY KEY,
postCount INT,
topicCount INT
);
drop table if exists topic;
CREATE TABLE topic (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(10),
userId INT,
postCount int ,
foreign key(userId)references user(id) on delete cascade
);
drop table if exists post;
CREATE TABLE post (
id INT AUTO_INCREMENT PRIMARY KEY,
content VARCHAR(10),
topicId INT,
userId int ,
foreign key(topicId)references topic(id) on delete cascade,
foreign key(userId)references user(id) on delete cascade
);
delimiter ;;
create trigger ai_topic after insert on topic for each row
begin
update user set topicCount=topicCount+1 where user.id=new.userId;
end;;
create trigger ad_topic after delete on topic for each row
begin
update user set topicCOunt=topicCount-1 where user.id=old.userId;
delete from post where topicId=old.id;
end;;
create trigger ai_post after insert on post for each row
begin
update user set postCOunt=postCount+1 where user.id=new.userId;
update topic set postCount=postCOunt+1 where topic.id=new.topicId;
end;;
create trigger ad_post after delete on post for each row
begin
update user set postCount=postCount-1 where user.id=old.userId;
update topic set postCOunt=postCOunt-1 where topic.id=old.topicId;
end;;
delimiter ;