Possible Duplicate:
php / Mysql best tree structure
I am currently coding a file system in PHP and MySQL.
Folders are stored in a database table "folders" with fields: "id", "name", "parent_id". I thought this would be the fastest way.
Files are stored on the system, linked by the database table "files" with fields "id", "name", "parent_id" and "realUrl".
Assuming I would create a path like this: One/Folder/After/Another/Folder. This is table "folder" then:
+++++++++++++++++++++++++++++
+ id | name | parent_id +
+----|----------|-----------+
+ 1 | One | 0 +
+ 2 | Folder | 1 +
+ 3 | After | 2 +
+ 4 | Another | 3 +
+ 5 | Folder | 4 +
It is obvious that it's not that simple to find out things like the path of a folder. When I request the data of folder "Folder", I would want to know the path to this specific folder. I couldn't figure a good way out with MySQL except for selecting ALL contents of the database table and then iterate through it with PHP. But that could take terribly long when I have thousands of folders?
What would you suggest? I thought about creating a seperate table "parents" where I store all dependencies:
++++++++++++++++++++++++++
+ folders_id | parent_id +
+------------|-----------+
+ 2 | 1 +
+ 3 | 1 +
+ 3 | 2 +
+ 4 | 1 +
+ 4 | 2 +
+ 4 | 3 +
+ 5 | 1 +
+ 5 | 2 +
+ 5 | 3 +
+ 5 | 4 +
So if I want to get the path from "One" to "Folder", I just have to
SELECT parent_id FROM parents WHERE folders_id=5
There is huge risk of making errors and it's just redundant data of course. So there might be a more intelligent solution? Could I even iterate through the table "folders" by MySQL commands directly?
Of course my question is also about speed. Is it faster to make multiple easy queries or better just one large to get my data?
With the table "parents" I can find out the path of the folders with one query (merging both tables) and some PHP. Without the table "parents", I don't know how except selecting all, which can't be the solution?