0
實際觸發。但是我如何在mysql-workbench中做到這一點。因此,我隨時在table1
有任何新記錄它創建一個新的記錄參考table1.id
到table2.parentid
?MySQL - 如何在table1使用MySQL工作臺創建新記錄時在table2下創建子記錄?
--- [OK] --- This is created
CREATE TABLE IF NOT EXISTS `test`.`table1` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NULL ,
PRIMARY KEY (`id`))
ENGINE = InnoDB
--- [FAIL] --- #1005 - Can't create table 'test.table2' (errno: 150)
CREATE TABLE IF NOT EXISTS `test`.`table2` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`parentid` VARCHAR(45) NULL ,
`table1_id` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_table2_table1` (`parentid` ASC) ,
CONSTRAINT `fk_table2_table1`
FOREIGN KEY (`parentid`)
REFERENCES `test`.`table1` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
追問:
1)MySQL工作臺不提供該
2)單擊表1>點擊觸發標籤底部>寫
-- trigger module initiate
DELIMITER $$
CREATE TRIGGER triggertest1 BEFORE INSERT ON table1
FOR EACH ROW BEGIN
INSERT INTO table2 SET parentid = NEW.id;
END;
$$
DELIMITER ; --- return to normal
爲什麼在我的觸發器中我總是有'NEW.id' == 0? table2.parentid總是顯示0. – YumYumYum 2012-02-27 09:16:28
原因很簡單,你的觸發器在插入到父表之前觸發,所以它不會找到任何id,因爲數據沒有被插入。將觸發器更改爲AFTER INSERT ON – 2012-02-27 09:41:19