简体   繁体   中英

MySQL insert with undefined foreign key

I have some table with such schema (simplified):

CREATE TABLE folders(
  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  parent INT(11) UNSIGNED NOT NULL,
  PRIMARY KEY (id),
  INDEX FK_folders_folders_id (parent),
  CONSTRAINT FK_folders_folders_id FOREIGN KEY (parent)
  REFERENCES folders (id) ON DELETE CASCADE ON UPDATE CASCADE
)

1 folder can have many subfolders and can belongs to one another folder. If it's root folder then parent will contain it's own ID.

The problem is: how can I create root folder? ID is auto_increment and I can get it only after inserting a row but I cant insert row while parent is not defined. Recursion...

You can remove the NOT NULL attribute from the parent field, this way you can have your root. Of course, in this case you have to garantee the folder tree cosistency in your code and not through database. MySQL reference manual does not advise users to do this:

You are advised to use foreign keys that reference only UNIQUE and NOT NULL keys. http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

but it's always up to you.

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