简体   繁体   English

MySQL插入与未定义的外键

[英]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. 1个文件夹可以具有许多子文件夹,并且可以属于另一个文件夹。 If it's root folder then parent will contain it's own ID. 如果它是根文件夹,那么父级将包含它自己的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. ID为auto_increment,我只能在插入一行后才能获取它,但是在未定义parent的情况下无法插入行。 Recursion... 递归...

You can remove the NOT NULL attribute from the parent field, this way you can have your root. 您可以从父字段中删除NOT NULL属性,这样便可以拥有根目录。 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: MySQL参考手册不建议用户这样做:

You are advised to use foreign keys that reference only UNIQUE and NOT NULL keys. 建议您使用仅引用UNIQUE和NOT NULL键的外键。 http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

but it's always up to you. 但它总是由您决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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