这是我想要创建的简单触发器:
CREATE TRIGGER add_item_id BEFORE INSERT ON products
FOR EACH ROW
BEGIN
DECLARE max_id INTEGER;
SELECT MAX(item_id) INTO @max_id FROM products;
SET NEW.item_id = @max_id + 1;
END;
我在phpMyAdmin SQL窗口和mysql提示符下都尝试过,并得到如下错误:
#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 4
答案 0 :(得分:1)
delimiter //
CREATE TRIGGER add_item_id BEFORE INSERT ON products
FOR EACH ROW
BEGIN
DECLARE max_id int;
SELECT MAX(item_id) INTO max_id FROM products;
SET NEW.item_id = max_id + 1;
END//
delimiter ;
一些注意事项:
delimiter //
,MySQL会看到以..FROM PRODUCTS;
结尾的CREATE TRIGGER语句,这会使其无效答案 1 :(得分:0)
你也可以这样做:
CREATE TRIGGER add_item_id
BEFORE INSERT
ON products
FOR EACH ROW
BEGIN
SET NEW.item_id = 1 + ( SELECT MAX(item_id)
FROM products
) ;
END;
注意:您可以在几乎所有RDBMS中声明auto_incremented字段。