0

在我有关于(分层数据的反向查询)分层数据的 反向查询的问题之前

我得到了 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

现在为了完全得到我的答案,我还有 1 个问题

我如何在我的查询中也有每个字段的位置。例如,TUBE、LCD、PLASMA 的父级是电视,现在我需要根据字母顺序给出每个位置(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
4

1 回答 1

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
于 2013-06-27T14:30:13.327 回答