1

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...

4
  • 1
    This is exactly where you need null Commented Feb 5, 2011 at 16:44
  • Why is parent it's own ID when the folder is in root? Wouldn't it be better to insert a zero (0) into it? Commented Feb 5, 2011 at 16:45
  • Impossible cause there's foreign key to ID that is NOT NULL (PRIMARY KEY) Commented Feb 5, 2011 at 16:45
  • off topic : read this : dev.mysql.com/tech-resources/articles/hierarchical-data.html and consider using the nested set model if you need to, it could spare you some headaches Commented Feb 5, 2011 at 16:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.