我正在尝试创建一个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;
$$
答案 0 :(得分:1)
要考虑的几点:
13.2.9.1. SELECT ... INTO Syntax
不应在嵌套的SELECT中使用INTO子句,因为这样 SELECT必须将其结果返回到外部上下文。
19.3.1. Trigger Syntax and Examples
这样的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 ;
答案 1 :(得分:0)
MySQL,或者至少我正在运行的版本,无法一次处理多个触发器。由于这个原因,IF语句不适用于BEGIN和END,所以我必须找到不同的解决方案。