我不知道该怎么说。我觉得我对SQL有很好的理解,但是我被难住了。
一点背景知识。
我在那张桌子上有一张表格GroupName, GroupId, ParentGroupId, ObjectRowState CustomersGroups
客户可以创建树型组结构。
parent
-Child
- - GrandChild
- - GreatGrandChild
etc. 如果用户删除了一个组,它将删除与其关联的所有子组。我希望能够找到一个组。然后在查询中使用该组作为其子组的父组ID,依此类推。
所以
SELECT *
FROM tbl_CustomersGroups
WHERE CompanyId = 123
And GroupName = North将结果转换为GroupID = 111
SELECT *
FROM Tbl_CustomersGroups
WHERE ParentGroupID = 111儿童GroupID 222,333,444的结果
然后,我想要一遍又一遍地查询,直到没有更多的组。通常有6层深。
我不想一遍又一遍地进行单独的查询,我想要一个很大的查询,我可以把它放在ParentGroupID中,它会循环下来,给我所有的子查询。
我不是要求写一个问题,我是要求如何去做的指导或例子。
发布于 2016-05-11 18:58:37
我希望这能对你有所帮助。您需要使用CTE (公共表表达式) https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx
CREATE TABLE #table (GroupName varchar(50),
GroupId int,
ParentGroupId int,
ObjectRowState varchar(50))
insert into #table values ('vehicle', 1, null, 'general vehicle')
insert into #table values ('Car', 2, 1, 'general cars')
insert into #table values ('2 doors car', 3, 2, 'cars with 2 doors')
insert into #table values ('4 doors car', 4, 2, 'cars with 4 doors')
insert into #table values ('Motorcycle', 5, 1, 'general Motorcycle')
insert into #table values ('Speed Motorcycle', 6, 5, 'Speed Motorcycle')
insert into #table values ('Road Motorcycle', 7, 5, 'Road Motorcycle')
insert into #table values ('Truck', 8, 1, 'General Truck')
insert into #table values ('Waggon', 9, 8, 'General Truck')
insert into #table values ('Airplane', 10, null, 'General Airplane')
insert into #table values ('Jet Airplane', 11, 10, 'General Jet Airplane')
insert into #table values ('Jet Fighter', 12, 11, 'General Jet Airplane')
;with cte (GroupName , GroupId , ParentGroupId , ObjectRowState, Grouplevel, RowOrder)
AS
(
SELECT GroupName,
GroupId,
ParentGroupId,
ObjectRowState,
1,
ROW_NUMBER() OVER (ORDER BY GroupId)
FROM #table
WHERE ParentGroupId IS NULL
UNION ALL
SELECT #table.GroupName,
#table.GroupId,
#table.ParentGroupId,
#table.ObjectRowState,
cte.Grouplevel + 1,
cte.RowOrder
FROM #table
INNER JOIN cte on cte.GroupId = #table.ParentGroupId
)
SELECT GroupName,
GroupId,
ParentGroupId,
ObjectRowState
FROM cte
ORDER BY cte.RowOrder, cte.Grouplevel
DROP TABLE #tablehttps://stackoverflow.com/questions/33311239
复制相似问题