当我在user_follows_user表中插入插入内容时,我试图创建一个触发器来计算用户的关注者数量。
我的触发器
DELIMITER |
CREATE TRIGGER increase_follower
AFTER INSERT ON user_follows_user FOR EACH ROW
BEGIN
DECLARE sum_followed_user INT;
SELECT COUNT(*) INTO @sum_followed_user FROM user_follows_user, users u WHERE u.user_name = NEW.followed_user;
UPDATE users SET follower = @sum_followed_user WHERE user_name = NEW.followed_user;
END;
|
用户表
CREATE TABLE users
(
user_name varchar(15) not null,
user_password varchar(68) not null,
birthdate date default null,
email varchar(45) not null,
city varchar(45) default null,
img varchar(45) default null,
rating INT default null,
PRIMARY KEY(user_name)
);
user_follows_user表
CREATE TABLE user_follows_user
(
following_user varchar(15) not null,
followed_user varchar(15) not null,
PRIMARY KEY(following_user,followed_user),
CONSTRAINT FK_FOLLOWING_USER
FOREIGN KEY (following_user)
REFERENCES users (user_name),
CONSTRAINT FK_FOLLOWED_USER
FOREIGN KEY (followed_user)
REFERENCES users (user_name)
);
我的插入
INSERT INTO users (user_name,user_password,email)VALUES("sakar","tmp","sakar@hotmail.de");
INSERT INTO artay_users (user_name,user_password,email)VALUES("amir","tmp2","amir@hotmail.de");
INSERT INTO artay_users (user_name,user_password,email)VALUES("phuc","tmp3","phuc@hotmail.de");
INSERT INTO artay_users (user_name,user_password,email)VALUES("can","tmp4","can@hotmail.de");
INSERT INTO user_follows_user(following_user, followed_user) VALUES ("sakar","can");
INSERT INTO user_follows_user(following_user, followed_user) VALUES ("phuc","amir");
INSERT INTO user_follows_user(following_user, followed_user) VALUES ("can","amir");
当我完全这样做时,我得到的是amir follower = 3,而可以得到follower = 1。即使我应该为amir获得2个关注者,并为can获得一个。