假设我有一个自引用的表,如下所示
------------------------------
| ID | Name | ParentID |
| 1 | Fruits | |
| 2 | Vegetables | |
| 3 | Animals | |
| 4 | Whatever | |
| 6 | Orange | 1 |
| 7 | Apple | 1 |
| 8 | Banana | 1 |
------------------------------
为了检索数据,我需要执行一个查询,如下所示:
------------------------------
| ID | Name | ParentID |
| 1 | Fruits | |
| 6 | Orange | 1 |
| 7 | Apple | 1 |
| 8 | Banana | 1 |
| 2 | Vegetables | |
| 3 | Animals | |
| 4 | Whatever | |
------------------------------
无论何时应用,都会在孩子面前显示父母。
发布于 2015-06-16 15:50:47
假设您使用的是SQL Server的某个变体,则需要使用包含某种路径/breadcrumb列的公用表表达式...
;with cte as
(
select Id, Name, ParentID,
convert(nvarchar(max), [Id]) as Breadcrumb
from dbo.Location
where ParentID is null
--
union all
--
select l.Id, l.Name, l.ParentID,
cte.BreadCrumb + '\' + convert(nvarchar(max), l.[Id]) as Breadcrumb
from dbo.Location l
inner join cte on l.ParentId = cte.Id
)
select *
from cte
order by Breadcrumb
编辑:您可以使用ID或名称作为您的面包屑值-取决于您想要如何对您的数据进行排序。
发布于 2015-06-16 15:54:40
如果SQL server:
select * from MyTable
order by
case when ID in (select distinct parentID from MyTable)
then ID - 0.5 else isnull(parentID, 100000) end
, ID
检查ID是否为父ID-如果是,则将其排序到将其作为父ID的记录的正上方(通过从ID中减去0.5 )。
注意:isnull(parentID, 100000)
只是一个任意的大值,用于将既不是父级也不具有父级的行放在列表的底部-根据您的数据根据需要进行调整。如果您有大量数据和/或数据频繁更改,则可能需要将100,000替换为基于表中最大ID的计算值。
https://stackoverflow.com/questions/30872197
复制