There is no single SQL query that can bring you the results ordered as you expect based on this table structure.
There are two ways to solve the problem:
Use the external logic of the application (outside the database) to make recursive calls that will open the children of each category and build a tree in the application.
Use one of the algorithms to store tree data in a relational database. One of these algorithms is called Modified Preorder Tree Traversal
or simply MPTT.
Assuming we use the lft
and rgt
to maintain indexes on the left and right when crawling, when you insert a new category, you need:
Get information about the parent category by identifier: SELECT lft,rgt FROM tbl_categories WHERE categoryId=5
Assume, as an example, the parent category had lft=7
and rgt=10
(in this case, she already has one child)
Make room for a new entry - shift all entries to 2 (1 for lft and 1 for rgt):
UPDATE tbl_categories SET rgt=rgt+2 WHERE rgt>=10 ORDER BY rgt DESC
UPDATE tbl_categories SET lft=lft+2 WHERE lft>=10 ORDER BY lft DESC
Note here ORDER
in descending order. Since lft
and rgt
must be unique, it is recommended to set the UNIQUE
restriction for them, and then, in order to prevent duplication of key errors, a descending order is required when updating.
Set lft=<former parent rgt>
and rgt=<former parent rgt +1>
and insert a new entry ...
INSERT INTO tbl_categories SET categoryName="New Child",parentCategoryId=5,lft=11,rgt=12,...
You can find more detailed code examples if you are looking for MPTT PHP MySQL
. There are quite a few textbooks on this subject.
source share