2

我正在尝试编写一个触发器来解决 innodb auto_increment 问题。我想让 orderID 是 auto_increment 但是 innodb 不允许我。这是 ORDER 表

CREATE TABLE IF NOT EXISTS `ORDER` (
  `placeID` INT UNSIGNED NOT NULL,
  `orderID` INT UNSIGNED NOT NULL,
  `userID` INT UNSIGNED NOT NULL ,
  `tableNum` SMALLINT NOT NULL,
  `orderStatus` TINYINT NOT NULL,
  `orderDate` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`placeID`,`orderID`),
  FOREIGN KEY (`userID`) REFERENCES `USER` (`userID`),
  FOREIGN KEY (`placeID`) REFERENCES `PLACE` (`placeID`))
ENGINE=InnoDB;

这是触发器

delimiter $$
DROP TRIGGER /*!50032 IF EXISTS */ `ORDER_TRIGGER` $$
CREATE TRIGGER `ORDER_TRIGGER` BEFORE INSERT ON `ORDER`
FOR EACH ROW
BEGIN
        DECLARE orderID INT UNSIGNED;
    SELECT MAX(`orderID`) INTO orderID FROM `ORDER` WHERE `placeID` = NEW.placeID;
        IF orderID IS NULL THEN
            orderID = 1;
        END IF;
    SET NEW.orderID = orderID+1;
END;
$$
delimiter;

当我执行这个脚本时,我得到了这个错误。

#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 '= 1;
        END IF;
    SET NEW.orderID = orderID+1;
END' at line 7 

有谁能够帮我?我查看了谷歌,但找不到准确的解决方案。

4

1 回答 1

2

我发现了我的错误。这是正确的代码。

delimiter $$
DROP TRIGGER /*!50032 IF EXISTS */ `ORDER_TRIGGER` $$
CREATE TRIGGER `ORDER_TRIGGER` BEFORE INSERT ON `ORDER`
FOR EACH ROW
BEGIN
        DECLARE orderID INT UNSIGNED;
        SELECT MAX(`ORDER`.`orderID`) AS ID INTO orderID FROM `ORDER` WHERE `ORDER`.`placeID` = NEW.placeID;
        IF orderID IS NULL THEN
            SET orderID = 0;
        END IF;
    SET NEW.orderID = orderID+1;
END;
$$
于 2012-07-04T08:19:58.950 回答