0

“需要显示所有链接到父类别的项目 id=1 根据表格,它应该获取:大机器、计算机、CPU 机柜、硬盘和磁盘。但是按照编写的逻辑,它并没有获取所有记录。请帮助..“

  create table ItemSpares
  (
        ItemName varchar(20),
        ItemID int,
        ParentCategoryID int
  )

  insert into ItemSpares (ItemName,ItemID,ParentCategoryID)
  select 'Big Machine', 1 , NULL UNION ALL
  select 'Computer', 2, 1 UNION ALL
  select 'CPU Cabinet', 3, 2 UNION ALL
  select 'Hard Disk', 4, 3 UNION ALL
  select 'Magnetic Disk',5,4 UNION ALL
  select 'Another Big Machine',6, NULL 
4

1 回答 1

0

您需要使用分层 SQL 查询,花了一段时间才弄清楚,但试试这个:

with BigComputerList (ItemName, ItemID, ParentCategoryID, Level) 
AS
(
-- Anchor member definition
    SELECT e.ItemName, e.ItemID, e.ParentCategoryID,
        0 AS Level
    FROM ItemSpares AS e
    WHERE ItemID = 1
    UNION ALL
-- Recursive member definition
    SELECT e.ItemName, e.ItemID, e.ParentCategoryID,
        Level + 1
    FROM ItemSpares AS e    
    INNER JOIN BigComputerList AS d
        ON e.ParentCategoryId = d.ItemID
)

Select * From BigComputerList

如果您想了解查询在做什么,我强烈建议您阅读这篇文章。

于 2013-09-22T19:10:02.540 回答