1
DECLARE @MAIN TABLE
(
  MainID INT NOT NULL, 
  Name VARCHAR(20) NOT NULL,
  [Deleted] BIT NOT NULL
);

DECLARE @ITEMS TABLE
(
  ItemID INT NOT NULL, 
  ParentItemID INT NULL,
  MainID INT NOT NULL, 
  Data VARCHAR(100) NOT NULL
);


INSERT INTO @MAIN (MainID, Name, [Deleted]) VALUES  (1, 'Tool 1', 0)
INSERT INTO @MAIN (MainID, Name, [Deleted]) VALUES  (2, 'Tool 2', 0)

INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (1, NULL, 1, 'Level 1')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (2, NULL, 1, 'Level 2')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (3, NULL, 2, 'Level 1 - Irrelevant')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (4, NULL, 1, 'Level 3')

INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (5, 1, 1, 'Item 1-A')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (6, 4, 1, 'Item 2-C')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (7, 7, 2, 'Item Irrelevant 1')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (8, 10, 1, 'Item 3-E')

INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (9, 1, 1, 'Item 1-B')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (10, 4, 1, 'Item 2-D')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (11, 7, 2, 'Item Irrelevant 2')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (12, 10, 1, 'Item 3-F')

INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (13, 5, 1, 'Item 1-A-1')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (14, 8, 1, 'Item 2-C-1')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (15, 5, 2, 'Item 1-A-2')
INSERT INTO @ITEMS (ItemID, ParentItemID, MainID, Data) VALUES (16, 9, 1, 'Item 1-B-1')


SELECT * FROM @MAIN
SELECT * FROM @ITEMS

问题 1:
检索属于ItemID = 1的所有记录的最简单方法是什么,所有记录都是递归子项目并按 ParentHood 排序。

问题 2:通过 ParentHood
检索所有记录顺序的最简单方法是什么。

非常感谢..在先进!

4

1 回答 1

4

您需要的是使用一个公用表表达式,它可以让您执行分层查询。

;With AllItems As
    (
    Select I.ItemId, Null As ParentItemId, M.MainId, M.Name, M.[Deleted]
    From @Items As I
        Join @Main As M
            On M.MainID = I.MainID
    Where ParentItemId Is Null
    Union All
    Select I.ItemId, I.ParentItemId, M.MainId, M.Name, M.[Deleted]
    From @Items As I
        Join AllItems As P
            On P.ItemId = I.ParentItemId
        Join @Main As M
            On M.MainID = I.MainID
    )
Select *
From AllItems

WITH common_table_expression (Transact-SQL)

SQL 小提琴示例

于 2012-05-24T02:55:04.740 回答