我想用父级检索所有类别,以便创建面包屑路径。因此我创建了以下架构:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
通过我遵循的示例,我可以使用以下SQL检索信息:
+-------------+----------------------+-------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+-------------+-------+
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
我发现的问题是在能够看到类别的完整路径之前我们必须知道它所处的级别。
我的问题是,有没有办法检索信息,如下例所示,但没有定义确切的级别数量?
ELECTRONICS
ELECTRONICS / TELEVISIONS
ELECTRONICS / TELEVISIONS / TUBE
ELECTRONICS / TELEVISIONS / LCD
ETC
ETC
我的想法是在考虑深度级别的情况下检索lev1或lev2等。
更新:
示例输出
HOLIDAYS_PER__WORK_DAY
答案 0 :(得分:1)
有一种解决方法。
您可以添加辅助PATH
列。该列应该具有从elemetn到parent的id链。因此对于根列空。 root的所有孩子都有_
+-------------+----------------------+--------+--------+
| category_id | name | parent | path |
+-------------+----------------------+--------+--------+
| 1 | ELECTRONICS | NULL | |
| 2 | TELEVISIONS | 1 |1_ |
| 3 | TUBE | 2 |1_2_ |
| 4 | LCD | 2 |1_2_ |
| 5 | PLASMA | 2 |1_2_ |
| 6 | PORTABLE ELECTRONICS | 1 |1_ |
| 7 | MP3 PLAYERS | 6 |1_6_ |
| 8 | FLASH | 7 |1_6_7_ |
| 9 | CD PLAYERS | 6 |1_6_ |
| 10 | 2 WAY RADIOS | 6 |1_6_ |
+-------------+----------------------+--------+--------+
在插入新节点时,您只需复制父节点路径并添加“_” 因此,要检索节点的所有子节点,只需使用
SELECT *
FROM THE_TABLE
WHERE PATH LIKE '<parent node path>%'
虽然
有字段大小和级别限制