Я пытаюсь создать триггер, который подсчитывает количество подписчиков от пользователя, когда у меня есть вставка в мою таблицу 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 и за can follower = 1.Хотя я должен получить 2 последователя за амира и одного за банку.