1

我在 SQL Server 中有一些分层类别,定义如下:

CREATE TABLE [dbo].[CategoryDesc] (
    [CategoryId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](255) NOT NULL
)

CREATE TABLE [dbo].[CategoryRelationship] (
    [RelationshipId] [int] IDENTITY(1,1) NOT NULL,
    [CategoryId] [int] NOT NULL,
    [ParentId] [int] NULL
)

CREATE TABLE [dbo].[Machine] (
    [MachineId] [int] IDENTITY(1,1) NOT NULL,
    [Make] [varchar](50) NOT NULL,
    [Model] [varchar](255) NOT NULL,
    [CreateDate] [datetime] NOT NULL,
    [CategoryId] [int] NOT NULL
)

注意:为简洁起见,省略了主键、关系和一些字段。

我已经使用 CTE 来生成一棵完整的树,其输出的摘录:

Foundry/Forging
Foundry/Forging > Core Equipment
Foundry/Forging > Furnaces
Foundry/Forging > Furnaces > Induction
Glass
Glass > Bevelling
Glass > Cutting
Glass > Cutting > Laminated Glass
Glass > Cutting > Manual
Glass > Cutting > Shape
Glass > Cutting > Straight
Glass > Decorating
Glass > Drilling
Glass > Drilling > Horizontal
Glass > Drilling > Vertical
etc

我需要一个给定顶级 categoryId 的查询,返回最新添加的机器(基于 CreateDate),而不管它添加了哪个子类别和在哪个级别。

我遇到的问题是机器可能被添加到第 2 或第 3 级类别(尽管从来不是顶级)并且 CTE 不允许在递归部分进行左连接。

提前感谢您提供的任何帮助。:)

4

1 回答 1

1

我已将您的架构简化为:

create table cat( id int, name varchar(100) );
create table tree ( id int , parent_id int);
create table item( id int, name varchar(100), cat_id int);

insert into cat values 
( 1, 'HW'),
( 2, 'HW-PC'),
( 3, 'HW-M' ),
( 4, 'Soft'),
(5,'HW-M-N');

insert into tree values
(2,1),
(3,1),
(5,3);

insert into item values 
( 1, 'A', 2),
( 2, 'B', 3);

对于根类别 = 1,您请求的查询是:

with child_id as
( 
  select parent_id as id
      from tree
      where parent_id = 1                         --here cat = 1
   union all
   select tree.id
   from child_id  c
   inner join tree on tree.parent_id = c.id
),
productes as (
   select item.*,
    row_number() over (order by item.id ) as rn  --set your order criteria
   from item 
   inner join child_id c on c.id = item.cat_id
)
select * 
 from productes
where rn = 1

结果

| ID | NAME | CAT_ID | RN |
---------------------------
|  1 |    A |      2 |  1 |
于 2012-12-11T17:46:33.760 回答