在我有关于(反向查询分层数据)的问题之前 Reverse query for Hierarchical Data
我得到了90%的答案。
select i.ID, l.lev1 as Name, NULL as Parent
from IDTable i
join LevelTable l on i.Name = l.lev1
union
select i.ID, l.lev2 as Name, (select j.ID from IDTable j where j.Name = l.lev1)
from IDTable i
join LevelTable l on i.Name = l.lev2
union
select i.ID, l.lev3 as Name, (select j.ID from IDTable j where j.Name = l.lev2)
from IDTable i
join LevelTable l on i.Name = l.lev3
现在为了完全得到我的回答我还有一个问题
如何在查询中找到每个字段的位置。例如,TUBE,LCD,PLASMA的父母是TELEVISIONS现在我需要位置字段值,根据字母顺序给出每个位置(0,1,2,3 ......)的值。
category_id | name | parent |position
+-------------+----------------------+--------+-------
| 1 | ELECTRONICS | NULL |0
| 2 | TELEVISIONS | 1 |0
| 3 | TUBE | 2 |3
| 4 | LCD | 2 |1
| 5 | PLASMA | 2 |2
答案 0 :(得分:0)
您应该能够将row_number()函数与分区一起使用。
select *, row_number() over (partition by parent order by name) as position from (
select i.ID, l.lev1 as Name, NULL as Parent
from IDTable i
join LevelTable l on i.Name = l.lev1
union
select i.ID, l.lev2 as Name, (select j.ID from IDTable j where j.Name = l.lev1)
from IDTable i
join LevelTable l on i.Name = l.lev2
union
select i.ID, l.lev3 as Name, (select j.ID from IDTable j where j.Name = l.lev2)
from IDTable i
join LevelTable l on i.Name = l.lev3
) as q