Search code examples
mysqlsqlselectnested-sets

How to SELECT for the following?


I have a table DOCUMENTS and a table FOLDERS

FOLDERS
ID
lft
rgt

DOCUMENTS
ID
folderID -> FOLDERS(ID)
title

So, what we have here is an arbitrarily deep tree of folders (nested-sets). Each folder can contain an arbitrary number of documents.

What is the most efficient way to SELECT all of the documents that are beneathe a certain folder? That is, I want to SELECT not only the documents that are in a folder, but the documents that are in that folder's subfolders.

Edit: Sample data to make things more clear:

FOLDERS
ID     LFT     RGT
1      1       10      
2      2       5
3      3       4
4      6       7
5      8       9

This represents a folder structure like so...

       1
    2  4  5
 3

Where 2, 4, 5 are children of 1, and 3 is a child of 2

Now...

Let's say DOCUMENTS has the following data...

DOCUMENTS
ID     FolderID    Title
1      5           Doc 1
2      3           Doc 2
3      2           Doc 3

Given the ID of a folder, I want to SELECT all of the documents in that folder, and all of the documents in that folder's subfolders. So for example given a folderID of 2, the SELECT would return documents 2 and 3

Thanks (in advance) for your help


Solution

  • First, you'll want to get the lft and rgt values from the folders table:

    select lft, rgt from folders where id = 2;
    

    ...then use those to identify documents that exist within that node or its children:

    select d.* from documents d left join folders f on f.id = d.folderID where f.lft >= 2 and f.rgt <= 5;
    

    You can call these two queries separately in your code, you could combine them with subqueries, or you could write a stored procedure that combines them.