这是我的桌子
CREATE TABLE IF NOT EXISTS `carslibrary` (
`CarID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`CarName` varchar(255) NOT NULL,
PRIMARY KEY (`CarID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
CREATE TABLE IF NOT EXISTS `colorslibrary` (
`ColorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ColorName` varchar(255) NOT NULL,
PRIMARY KEY (`ColorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `facerecord` (
`carslibrary_ID` int(10) unsigned NOT NULL,
`colorslibrary_ID` int(11) unsigned NOT NULL,
KEY `carslibrary_ID` (`carslibrary_ID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;我注意到facerecord表中的carslibrary_ID属性没有自动更新,当我在carslibrary表中添加一个汽车记录时,我应该怎么做才能做到?
发布于 2011-10-06 15:35:58
首先,您需要为facerecord.colorslibrary_ID指定一个默认值,因为在插入到carslibrary表中时,您不会“知道”它是什么。也就是说,您可以将facerecord表的DDL更改为:
CREATE TABLE `facerecord` (
`carslibrary_ID` int(10) unsigned NOT NULL,
`colorslibrary_ID` int(10) unsigned NOT NULL DEFAULT '0',
KEY `carslibrary_ID` (`carslibrary_ID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;我还更改了colorslibrary_ID列的数据类型,以便与colorslibrary.ColorID列的数据类型相匹配,以防您想在facerecord.colorslibrary_ID和colorslibrary.ColorID之间设置外键;)。出于完整性的考虑,您应该在colorslibrary表中插入一行ColorID = 0的行。因此:
insert into `colorslibrary` (ColorName) values ('unknown color');
update `colorslibrary` set ColorID = 0 where ColorName = 'unknown color';然后,您可以继续定义触发器以插入到facerecord表中:
delimiter $$
CREATE TRIGGER carslibrary_trigger
AFTER insert ON carslibrary
FOR EACH ROW
BEGIN
insert into facerecord (carslibrary_ID) values (new.CarID);
END$$
delimiter;然后,插入到facerecord表中的所有新行都将插入一个与“未知颜色”相关的colorslibrary_ID。colorslibrary.ColorName.You随后可以在您知道的时候手动更新facerecord.colorslibrary_ID。
祝好运!
PS如果您需要从carslibrary表中删除任何现有的AFTER insert触发器,您可以通过首先找到现有的触发器来执行此操作:
select trigger_name
from information_schema.triggers
where event_object_table = 'carslibrary'
and action_timing = 'AFTER'
and event_manipulation= 'INSERT';然后获取由上述语句返回的触发器的名称(假设返回字符串'carslibrary_trigger‘)并运行:
drop trigger carslibrary_trigger;然后重新运行CREATE TRIGGER脚本。
一旦设置了触发器,当您指定的触发器操作发生时,它将自动执行您指定的操作。在本例中,我们告诉数据库“在插入到facerecord表之后,将使用新carslibrary行的CarID自动将一行插入到facerecord.carslibrary_ID表中,以填充facerecord.carslibrary_ID列”。和大多数事情一样,最好的方法就是尝试一下!一旦你手动创建了触发器,在'carslibrarytable. Now look at the data in thefacerecord`表中插入一个新的行--你应该会看到触发器触发插入了一个新行。
听起来你会从学习触发器中受益。我推荐MySQL site上的文档,因为这个答案比我最初预期的要长得多!
发布于 2011-10-06 13:50:30
您将需要使用触发器。请参阅http://dev.mysql.com/doc/refman/5.0/en/triggers.html
https://stackoverflow.com/questions/7670662
复制相似问题