简体   繁体   中英

MySQL workbench - self referring table and custom script

I use MySQL 5.3.28 to create my database. One of the tables is referring itself, which is a big pain. Here is the originally created code:

CREATE  TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL , 
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
 PRIMARY KEY (`ActivityId`) ,
 INDEX `Prerequisition` (`ActivityId` ASC) ,
 CONSTRAINT `Prerequisition`
 FOREIGN KEY (`ActivityId` ) 
 REFERENCES `dhbpsychiatry`.`activity` (`ActivityId` )

 ON DELETE NO ACTION
 ON UPDATE NO ACTION)

Problem is of course with creating first row.

INSERT INTO `dhbpsychiatry`.`activity` (`ActivityId`, `Prerequisition`,
`ActivityName`) VALUES (1, 1, 'No prerequisition');

returns

  ERROR 1452: Cannot add or update a child row: a foreign key constraint fails 

Same if I try even simpler

INSERT INTO `dhbpsychiatry`.`activity` (`ActivityName`) 
VALUES ('No prerequisition');

I think I've tried all possibilities, making the FK nullable, not nullable, with or without default value...

After digging a bit I've found something that works:

SET FOREIGN_KEY_CHECKS = 0;
Insert into activity (ActivityID, ActivityName) VALUES (0,'No prerequisition');
SET FOREIGN_KEY_CHECKS = 1;

So I created a new SQL script in workbench with those lines.

So I have two questions here:

  1. How I can add the first row without the script?

or if its impossible

2 How can I automatically add this script to be executed whenever I froward engineer the database?

Your indexes and Foreign key definitions are confused. Main issue is that column ActivityId is referencing itself.

Try this:

CREATE  TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL , 
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
 PRIMARY KEY (`ActivityId`) ,
 INDEX `Prerequisition_idx` (`Prerequisition`) ,  --- changed the index name
                                                  --- and the indexed column

 CONSTRAINT `Prerequisition_fk`                   --- changed the constraint name

   FOREIGN KEY (`Prerequisition` )                --- main issue !! changed  
                                                  --- the referencing column
   REFERENCES `dhbpsychiatry`.`activity` (`ActivityId`)
     ON DELETE NO ACTION
     ON UPDATE NO ACTION
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM