创建 SQL 触发器以更新另一个 table 时出错

Error when creating SQL trigger to update another table

我在“ON”或接近“ON”时遇到 语法错误,代码如下。写这个的正确方法是什么?我正在尝试为 game_info table 创建一个触发器,它将在数据添加到 game_info.

时更新 game_count table
CREATE TRIGGER my_trigger
    ON game_info
    AFTER INSERT
AS
BEGIN
    INSERT INTO game_count(title,count)
    SELECT title, count(*)
    FROM public.game_info
    GROUP BY title
    ORDER BY count DESC
END

创建 game_info table

CREATE TABLE game_info (
rental_id INT NOT NULL,
film_id SMALLINT NOT NULL,
title CHAR(255) NOT NULL,
description TEXT NOT NULL,
length SMALLINT NOT NULL
);

创建 game_count table

CREATE TABLE game_count (
title CHAR(255) NOT NULL,
count BIGINT NOT NULL
)

正在将数据插入 game_info

INSERT INTO game_info (rental_id, film_id, title, description, length)
SELECT
r.rental_id,
i.film_id,
f.title,
f.description,
f.length
FROM public.inventory as i
INNER JOIN public.rental as r ON r.inventory_id=i.inventory_id
INNER JOIN public.film as f ON f.film_id=i.film_id

正在将数据插入 game_count

INSERT INTO game_count(title, count)
SELECT title, count(*)
FROM public.game_info
GROUP BY title
ORDER BY count DESC;

你可以试试:

DELIMITER $$
CREATE TRIGGER my_trigger AFTER INSERT ON game_info
FOR EACH ROW
BEGIN
    INSERT INTO game_count set title=new.title, count=(select count(*) from FROM game_info GROUP BY title) ;    
END$$
DELIMITER ;

trigger 甚至对 game_info table 上的多个插入值也有效。