1

たとえば、以下のようなテーブルがある場合:-

    create table Categories(CategoryId int primary key,
 ParentCategoryId int foreign key references Categories(CategoryId))

たとえば、テーブルに次のデータがある場合:-

CategoryID  ParentCategoryId
1           2
2           3
3           4
4           NULL
5           6
6           7
7           NULL
8           9
9           NULL

Result:     

CategoryId  ParentCategoryId
1           4
2           4
3           4
4           NULL
5           7
6           7
7           NULL
8           9
9           NULL

助けてくれてありがとう!

4

3 に答える 3

1

これが再帰的な CTE ソリューションです。おそらくよりエレガントで効率的ですか?

WITH TopLevelParents AS (
    SELECT CategoryID, ParentCategoryID
    FROM Categories
    WHERE ParentCategoryID IS NULL
    UNION ALL
    SELECT c.CategoryID, ISNULL(p.ParentCategoryID, p.CategoryID) ParentCategoryID
    FROM Categories c
    JOIN TopLevelParents p ON c.ParentCategoryID = p.CategoryID
)
SELECT *
FROM TopLevelParents
ORDER BY 1
于 2012-05-07T19:26:55.160 に答える
1

SQL では、次のように実行できます。

DECLARE @childId int
SET @childId = 1

DECLARE @nextId int
DECLARE @currentId int

SET @nextId = @childId

WHILE (NOT (@nextId IS NULL))
BEGIN
    SET @currentId = @nextId

    SELECT @nextId = ParentCategoryId
    FROM Categories
    WHERE CategoryId = @currentId
END

SELECT @currentId AS RootCategoryId

Linq では、次のようなものを見ています。

public int GetRootCategoryId(int childId)
{
    int? nextId = childId
    int? currentID;

    while (nextID != null)
    {
        currentID = nextID;
        nextID = (from category in db.Categories
                 where category.CategoryId = currentID
                 select category.ParentCategoryId).First();
    }

    return currentID;
}
于 2012-05-07T18:42:54.103 に答える
1
CREATE TABLE #Parents (CategoryID INT PRIMARY KEY, ParentCategoryID INT)
INSERT #Parents
SELECT *
FROM Categories
WHILE @@ROWCOUNT != 0 BEGIN
    UPDATE p
    SET p.ParentCategoryID = c.ParentCategoryID
    FROM #Parents p
    JOIN Categories c ON p.ParentCategoryID = c.CategoryID
    WHERE c.ParentCategoryID IS NOT NULL
END
SELECT *
FROM #Parents
ORDER BY 1
DROP TABLE #Parents
于 2012-05-07T18:54:51.867 に答える