创建 SQL 触发器以更新另一个表时出错
Posted
技术标签:
【中文标题】创建 SQL 触发器以更新另一个表时出错【英文标题】:Error when creating SQL trigger to update another table 【发布时间】:2021-09-21 03:22:31 【问题描述】:我在“ON”处或附近得到语法错误,代码如下。写这个的正确方法是什么?我正在尝试为 game_info 表创建一个触发器,该触发器将在将数据添加到 game_info 时更新 game_count 表。
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 表
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 表
CREATE TABLE game_count (
title CHAR(255) NOT NULL,
count BIGINT NOT NULL
)
将数据插入游戏信息
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;
【问题讨论】:
将after insert
移到on game_info
上方,再试一次
@zedfoxus 它给了我错误消息“在“AS”或附近出现语法错误
删除 as
并重试。另外,请遵循以下教程:mysqltutorial.org/create-the-first-trigger-in-mysql.aspx 和 w3resource.com/mysql/mysql-triggers.php#MTAI
您的触发逻辑似乎有误。在当前状态下(在语法修复之后),它将为每个插入的行插入一堆新行到目标表中......也许您需要更新现有行中的数据(并在相应的游戏行不存在时插入新行) ?
【参考方案1】:
你可以试试:
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
表上的多个插入值。
【讨论】:
以上是关于创建 SQL 触发器以更新另一个表时出错的主要内容,如果未能解决你的问题,请参考以下文章