问题
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