将字段的默认值设置为auto_increment值 [英] Set default value of field to auto_increment value
问题描述
我有一个表,其中有一个自动递增列 id
和另一列 ord
。
I have a table where I have an auto increment column id
and another column ord
.
我的目标是使 ord
的默认值为 id
。我正在使用触发器(请参见下文),但是它始终使用 0
而不是 id
值。
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.
当我从 id
中删除auto_increment时,它会正常工作。 如何将字段的默认值设置为auto_increment字段之一?
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?
表
CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ord` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
触发
CREATE TRIGGER `ord_ai` BEFORE INSERT ON `mytable`
FOR EACH ROW IF NEW.ord IS NULL THEN
SET NEW.ord := NEW.id;
END IF
推荐答案
阅读下一个<$ INFORMATION_SCHMEA.TABLES
中id字段的c $ c> AUTO_INCREMENT 值,并将其用于 ord
字段。
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 ;
这篇关于将字段的默认值设置为auto_increment值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!