0

我有一个我正在尝试创建的 MySQL 触发器,但语法不正确。

触发器应该通过并匹配一组关键字与插入数据库的新帖子的标题。如果找到匹配项,则应将新帖子分配给该存储桶并更新存储桶的关键字集。如果未找到匹配项,则应使用帖子中的值创建一个新存储桶。错误指向以 IF EXISTS 开头的行,但我不知道出了什么问题。任何帮助将不胜感激。谢谢!


更新:代码已更新以退出 IF EXISTS,但现在我从 ELSE 语句开始出现错误。

delimiter $$

CREATE TRIGGER bucket_trigger_v1 BEFORE INSERT ON posts
FOR EACH ROW
  BEGIN
    set @target = NEW.post_title;
    set @bucket_id_number = '';
    set @bucket_relevance = '';

    SELECT idbuckets, MATCH (keywords) AGAINST (@target) AS score INTO @bucket_id_number, @bucket_relevance FROM buckets WHERE MATCH (keywords) AGAINST (@target) ORDER BY score DESC LIMIT 1;
    IF (@bucket_id_number != '') THEN
      BEGIN
        SET NEW.buckets_idbuckets = @bucket_id_number;
        UPDATE buckets SET keywords = concat(keywords, @target) WHERE idbuckets = @bucket_id_number;
      END
      ELSE
      BEGIN
        INSERT INTO buckets (idbuckets, keywords, creationdate) VALUES (, @target, NEW.postdate);
        SET NEW.bucket_idbuckets = (SELECT LAST_INSERT_ID());
      END
    END IF;
END;

$$
4

2 回答 2

1

需要考虑的几点:

13.2.9.1。SELECT ... INTO 语法

INTO 子句不应在嵌套的 SELECT 中使用,因为这样的 SELECT 必须将其结果返回到外部上下文。

19.3.1. 触发器语法和示例

这样的 SET 语句在 AFTER 触发器中无效,因为行更改已经发生。

更新

以下代码正确创建触发器。创建表posts只是为了创建触发器。

/*Table structure for table `posts` */

DROP TABLE IF EXISTS `posts`;

CREATE TABLE `posts` (
  `post_title` VARCHAR(500) DEFAULT NULL,
  `buckets_idbuckets` INT(11) DEFAULT NULL,
  `postdate` DATETIME DEFAULT NULL
) ENGINE=INNODB;

/* Trigger structure for table `posts` */

DELIMITER $$

/*!50003 DROP TRIGGER*/ /*!50032 IF EXISTS */ /*!50003 `bucket_trigger_v1` */$$

CREATE TRIGGER `bucket_trigger_v1` BEFORE INSERT ON `posts`
FOR EACH ROW
BEGIN
    SET @target := new.`post_title`;
    SET @bucket_id_number := '';
    SET @bucket_relevance := '';
    SELECT `idbuckets`, MATCH (`keywords`) AGAINST (@target) AS `score` INTO @bucket_id_number, @bucket_relevance FROM `buckets` WHERE MATCH (`keywords`) AGAINST (@target) ORDER BY `score` DESC LIMIT 1;
    IF (@bucket_id_number != '') THEN
        SET new.`buckets_idbuckets` := @bucket_id_number;
        UPDATE `buckets` SET `keywords` = CONCAT(`keywords`, @target) WHERE `idbuckets` = @bucket_id_number;
    ELSE
        INSERT INTO `buckets` (`keywords`, `creationdate`) VALUES (@target, new.`postdate`);
        SET new.`buckets_idbuckets` := LAST_INSERT_ID();
    END IF;
END$$

DELIMITER ;
于 2013-11-05T21:05:30.773 回答
0

MySQL,或者至少是我正在运行的版本,不能同时处理多个触发器。因此,IF 语句不适用于 BEGIN 和 END,因此我必须找到不同的解决方案。

于 2013-11-05T23:37:07.690 回答