我有一个查询“SELECT CASE”语句正常工作:
SELECT
(CASE `t`.`is_combined`
WHEN 0
THEN `t`.`topic_id`
ELSE `t`.`is_combined`
END) AS`group_id`,
SUM(`ctt`.`tm_download_status`) AS `is_downloaded`,
COUNT(`t`.`topic_id`) AS `group_topics_cnt`,
(SUM(`ctt`.`tm_download_status`) = COUNT(`t`.`topic_id`)) AS `is_downloaded_group`
FROM (`catalog_topics` `t` LEFT JOIN `catalog_tracker_torrents` `ctt` ON((`ctt`.`topic_id` = `t`.`topic_id`)))
WHERE (`t`.`topic_id` != 0)
GROUP BY (`group_id`)
所以,我想创建一个类似的触发器来更新“交叉”表:
DELIMITER $$
CREATE TRIGGER `tdg_ins_by_topics` AFTER INSERT ON `catalog_topics` FOR EACH ROW
BEGIN
REPLACE INTO catalog_topics_downloaded_groups(
SELECT (
CASE `t`.`is_combined`
WHEN 0
THEN `t`.`topic_id`
ELSE `t`.`is_combined`
END
) AS `group_id` ,
SUM( `ctt`.`tm_download_status` ) AS `is_downloaded` ,
COUNT( `t`.`topic_id` ) AS `group_topics_cnt` , (
SUM( `ctt`.`tm_download_status` ) = COUNT( `t`.`topic_id` ) ) AS `is_downloaded_group`
FROM `catalog_topics` `t`
LEFT JOIN `catalog_tracker_torrents` `ctt` ON `ctt`.`topic_id` = `t`.`topic_id`
WHERE `t`.`topic_id`
IN (
NEW.`topic_id`
)
GROUP BY `group_id`
)
END ;
$$
但收到错误消息:
“#”1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 在第14行'END'附近
看起来MySQL不理解CASE
语句中TRIGGER
与CASE
语句中SELECT
之间的差异。那么,我怎么能解决这个问题呢?
感谢您的回答。
答案 0 :(得分:2)
我认为您需要使用;
“结束”您的REPLACE语句,就像您必须使用分隔符结束TRIGGER
或PROCEDURE
/ FUNCTION
内的所有语句一样。
这就是为什么你将DELIMETER更改为$$
..所以你可以使用;
将mysql默认分隔符存储在触发器代码中。 (并使用更改的$$
分隔符结束创建触发器语句)
DELIMITER $$
CREATE TRIGGER `tdg_ins_by_topics` AFTER INSERT ON `catalog_topics` FOR EACH ROW
BEGIN
REPLACE INTO catalog_topics_downloaded_groups(
SELECT ( CASE `t`.`is_combined`
WHEN 0
THEN `t`.`topic_id`
ELSE `t`.`is_combined`
END
) AS `group_id`,
SUM(`ctt`.`tm_download_status`) AS `is_downloaded`,
COUNT( `t`.`topic_id` ) AS `group_topics_cnt` ,
(
SUM( `ctt`.`tm_download_status` ) = COUNT( `t`.`topic_id` ) ) AS `is_downloaded_group`
FROM `catalog_topics` `t`
LEFT JOIN `catalog_tracker_torrents` `ctt` ON `ctt`.`topic_id` = `t`.`topic_id`
WHERE `t`.`topic_id` IN ( NEW.`topic_id` )
GROUP BY `group_id`
);
END;
$$
DELIMETER ;