I'm trying to model a directory tree in MySQL, my first idea was:
CREATE TABLE Folder (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (255) NOT NULL,
parentId INT UNSIGNED,
UNIQUE INDEX (name, parentId),
CONSTRAINT FOREIGN KEY (parentId) REFERENCES Folder (id)
)
But due to the fact that MySQL allows multiple NULLs in a unique index, with this definition I could have 2 folders with the same name at root level like so:
id | name | parentId
----------------------
1 | a | null
2 | a | null
Can you find a way to have both of the following?
- a foreign key preventing a folder from being the child of a non-existing folder
- a uniqueness constraint preventing a folder from containing two files with the same name