Set default value of field to auto_increment value

2019-09-18 00:14发布

I have a table where I have an auto increment column id and another column ord.

My goal is to have a 'default' value for ord that is id. I am using a trigger (see below), but it always uses 0 instead of the id value.

When I remove the auto_increment from id, it works as it should. How can I set the 'default' value of a field to the one of an auto_increment field?

Table

CREATE TABLE IF NOT EXISTS `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ord` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

Trigger

CREATE TRIGGER `ord_ai` BEFORE INSERT ON `mytable`
 FOR EACH ROW IF NEW.ord IS NULL THEN
    SET NEW.ord := NEW.id;
END IF

1条回答
冷血范
2楼-- · 2019-09-18 00:54

Read the next AUTO_INCREMENT value of the id field from INFORMATION_SCHMEA.TABLES and use it for ord field.

delimiter //

drop trigger if exists ord_ai //

CREATE TRIGGER `ord_ai` BEFORE INSERT ON `mytable`
FOR EACH ROW 
BEGIN
  IF NEW.ord IS NULL THEN
    SET NEW.ord := ( SELECT AUTO_INCREMENT 
                       FROM INFORMATION_SCHEMA.TABLES
                      WHERE TABLE_NAME = 'mytable'
                        AND TABLE_SCHEMA = DATABASE() );
  END IF;
END;
//

delimiter ;
查看更多
登录 后发表回答