1

我有一个运行正常的“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 不理解CASEin TRIGGERstatement 和CASEin SELECTstatement 之间的区别。那么,我该如何解决这个问题?

感谢您的回答。

4

1 回答 1

2

我认为您需要“结束”您的 REPLACE 语句,;就像您必须用分隔符结束 a TRIGGERor 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 ;
于 2012-04-27T06:49:00.773 回答