我在为一组用户 ID 编写将排名列设置为最大排名值加 1 的触发器时遇到了困难。也许代码会比我的描述更有帮助:
CREATE TABLE `saved_listing` (
`saved_listing_id` int(10) NOT NULL auto_increment,
`user_id` int(10) NOT NULL default '0',
`listing_id` int(10) NOT NULL default '0',
`listing_ty` varchar(10) NOT NULL default '',
`notes` text NULL,
`rank` int(10) NOT NULL default '0',
`modify_by` int(10) NOT NULL default '1',
`modify_dt` timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`create_by` int(10) NOT NULL default '1',
`create_dt` datetime NOT NULL default '0000-00-00 00:00:00',
`active` enum('Yes','No') NOT NULL default 'No',
PRIMARY KEY (`saved_listing_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
这是我的触发代码:
CREATE TRIGGER ins_saved_listing BEFORE INSERT ON saved_listing
FOR EACH ROW BEGIN
SET NEW.create_dt = NOW();
SET NEW.rank = (SELECT MAX(rank) + 1 FROM saved_listing WHERE user_id = NEW.user_id);
END
这是我收到的错误消息:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
如有任何帮助,我们将不胜感激。我没有太多编写触发器的经验。
MySQL服务器版本:5.1.49-3~bpo50+1
最佳答案
那是因为mysql看到了;
(分隔符),中断了CREATE TRIGGER
的执行
试着改成:
delimiter |
CREATE TRIGGER ins_saved_listing BEFORE INSERT ON saved_listing
FOR EACH ROW BEGIN
SET NEW.create_dt = NOW();
SET NEW.rank = (SELECT MAX(rank) + 1 FROM saved_listing WHERE user_id = NEW.user_id);
END;
|
delimiter ;
关于MySQL 触发器将列设置为 max + 1 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5240838/