how implement a folder, subfolder in a Database
mysql, php, recursion, relational-database, sql
Solution
you're in danger of implementing an SQL anti pattern called naive trees. See the pdf of the book, it shows several good solutions.
Problem
I'm having a problem with logic programming, but I think that could be another solution much easier to do this in a SQL command, however, let's go to the problem. I have a table in MySQL (InnoDb) like this: ``` CREATE TABLE IF NOT EXISTS `folder` ( `id` INT NOT NULL AUTO_INCREMENT , `folder_id` INT NOT NULL , `name` VARCHAR(100) NULL , `hidden` TINYINT(1) NOT NULL DEFAULT 0 , PRIMARY KEY (`id`) , INDEX `fk_folder_folder1` (`folder_id` ASC) , CONSTRAINT `fk_folder_folder1` FOREIGN KEY (`folder_id` ) REFERENCES `folder` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB ``` It seems like a pretty simple, but I want to list the folders, in a way that the subfolders of this folder will appear below it. Like in any file repository. For example: In the table: ``` id name folder_id 1 root 1 2 etc 1 3 dev 1 4 apache 2 5 php 2 6 mysql 2 7 hda 3 8 hda1 3 9 lib 1 ``` I want to show it like this: ``` root etc apache php mysql dev hda hda1 lib ``` The question is, have a way to do this by SQL command or in PHP? I try make in PHP, and I don't see a way without a recursive function. But i haven't success. Solution: Because the MySQL doesn't accept the WITH clause, the recursive function in SQL is out of the box. Thanks guys. ``` SELECT c2.name FROM folder c1 LEFT OUTER JOIN folder c2 ON c2.folder_id = c1.id WHERE c2.folder_id = 1 // the id of the parent folder AND c2.id != c2.folder_id // Remove the parent folder ORDER BY c2.folder ASC ```