Set default value of field to auto_increment value

北慕城南 提交于 2019-12-25 03:56:07

问题


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:


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 ;


来源:https://stackoverflow.com/questions/23083449/set-default-value-of-field-to-auto-increment-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!