SQL Server:选择父子
我有 SQL Server 2008 ,其中有一个名为 ProductCategories 的表,设计如下:
Id | Name | ParentId
71 PCs NULL
32 MACs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
11 Keyboard 2
7 Mouse 2
8 Screen 2
我想从此表中进行选择,并获得如下结果集:
Id | Name | ParentId
71 PCs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
32 MACs NULL
11 Keyboard 2
7 Mouse 2
8 Screen 2
我尝试了这个,但是这显然首先给了我那些没有 ParentId 的:
WITH Hierarchy
AS
(
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
WHERE
T1.parentid IS NULL OR
T1.parentid IN (SELECT id from ProductCategories WHERE parentid IS NULL)
UNION ALL
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
INNER JOIN
Hierarchy TH ON TH.Id = T1.ParentId
)
select *
from Hierarchy
order by parentid
如果可以的话,请帮助我:)
-- 不懂 SQL 的人
I have SQL Server 2008 with a table called ProductCategories designed like this:
Id | Name | ParentId
71 PCs NULL
32 MACs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
11 Keyboard 2
7 Mouse 2
8 Screen 2
I would like to select from this table, and get a result set like this:
Id | Name | ParentId
71 PCs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
32 MACs NULL
11 Keyboard 2
7 Mouse 2
8 Screen 2
I tried this, but that obviously gives me the ones with no ParentId first:
WITH Hierarchy
AS
(
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
WHERE
T1.parentid IS NULL OR
T1.parentid IN (SELECT id from ProductCategories WHERE parentid IS NULL)
UNION ALL
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
INNER JOIN
Hierarchy TH ON TH.Id = T1.ParentId
)
select *
from Hierarchy
order by parentid
Please help me, if you can :)
--
The guy who doesn't know SQL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
三个 Order By 谓词,
try this:
Three Order By predicates,
试试这个
顺便说一句,表中的前两个索引不应该是 1 和 2,而不是 71 和 32 吗?
Try this
Btw, shouldn't first two indexes in your table be 1 and 2, not 71 and 32 ?