欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

sqlite树型结构查询

程序员文章站 2022-03-28 12:03:50
...

sqlite树型结构查询 表结构:tblCity(ID, ParentID, Name) 因为sqlite 没有row_number函数,也不能递归查询,所幸它有RowID 这个字段。只好采用这种 笨方法 1) [sql] select ID,Name,1 as Level from tblCity where ParentID=0 union all select a.ID,a.Nam

sqlite树型结构查询

表结构:tblCity(ID, ParentID, Name)

因为sqlite 没有row_number函数,也不能递归查询,所幸它有RowID 这个字段。只好采用这种 笨方法

1)

[sql]

select ID,Name,1 as Level from tblCity where ParentID=0

union all

select a.ID,a.Name,c.RowID as Level from tblCity a

inner join tblCity b on a.ParentID=b.ID

inner join

(

select ParentID from tblCity group by ParentID

) c on a.ParentID=c.ParentID

2)

[sql]

select ID,Name,1 as Level from tblCity where ParentID=0

union all

select a.ID,a.Name,c.RowID as Level from tblCity a

inner join tblCity b on a.ParentID=b.ID

inner join

(

select ParentID from tblCity group by ParentID

) c on a.ParentID=c.ParentID