Reputation: 1329
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...
Upvotes: 1
Views: 646
Reputation: 153
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.
Upvotes: 1