简体   繁体   English

创建 SQL 触发器

[英]Create a SQL trigger

Helloo !你好!

So I am a bit noob in SQL and I'm trying to create a trigger to get the average score of a movie.所以我在 SQL 中有点菜鸟,我正在尝试创建一个触发器来获得电影的平均分数。

I got three tables, users, relation and movies:我有三个表,用户,关系和电影:

  • In users there is an id, name, pwd, etc.在用户中有一个 id、name、pwd 等。

  • In movies there is an id, title, director and averageScore (that I在电影中,有一个 id、title、director 和 averageScore(我
    want to update)想更新)

  • In relation there is the user ID called idUser, the movie ID called相关的用户 ID 称为 idUser,电影 ID 称为
    idMovie and the score idMovie 和分数

So each time that a user adds a movie, there is a new relation row with the id of the User, the id of the movie and the score that the user gives因此,每次用户添加电影时,都会有一个新的关系行,其中包含用户的 id、电影的 id 和用户给出的分数

I want to make an average of the score for each movie each time that a new relation is created每次创建新关系时,我想对每部电影的得分进行平均

So for that I create this trigger所以为此我创建了这个触发器

CREATE TRIGGER Average
AFTER INSERT ON relation
FOR EACH ROW
    UPDATE movies
    SET averageScore = (SELECT AVG(score) FROM relation WHERE movies.id = relation.idMovie)

But when a new relation is created, the averageScore of movies doesn't change, and I can't find the problem.但是当一个新的关系被创建时,电影的averageScore并没有改变,我也找不到问题所在。 Please help me !请帮我 ! x) X)

The trigger was a good start, but you missed some points.触发器是一个好的开始,但你错过了一些要点。

movies.id is not part of relations the new values you adress with NEW.idMovie movies.id 不属于您与 NEW.idMovie 所处理的新值的关系

The last is you have to specify the row you want to update.最后是您必须指定要更新的行。

 CREATE TABLE movies(id int, averageScore DECIMAL(4,2)); CREATE TABLE relation(iduser INT, idMovie INT,score DECIMAL(4,2));
 INSERT INTO movies VALUES (1,0),(2,0);
 CREATE TRIGGER Average AFTER INSERT ON relation FOR EACH ROW UPDATE movies SET averageScore = (SELECT AVG(score) FROM relation WHERE idMovie = NEW.idMovie) WHERE movies.id = NEW.idMovie
 INSERT INTO relation VALUES (1,1,0.5),(2,1,0.7),(3,1,0.2)
 SELECT * FROM movies;
 id |编号 | averageScore -: |平均分 -: | -----------: 1 | ------------: 1 | 0.47 2 | 0.47 2 | 0.00 0.00

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM