我需要从三个表中选择查询以显示项目和子项目(级别开启)和子子项目(级别2),我的问题是当我选择使用连接时,我在查询结果中获得的不仅仅是item1如果item1有多个子,所以我需要查询来完成这个菜单,这就是三个表。
CREATE TABLE [dbo].[Category] (
[CategoryID] [int] PRIMARY KEY IDENTITY ,
[CategoryName] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Remarks] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CategorySub] (
[SubCategoryID] [int] NOT NULL ,
[CategoryIDToSub] [int] NULL ,
[SubCategoryName] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[RcatID] [int] NULL ,
[RsubID] [int] NULL ,
[Rsub2ID] [int] NULL ,
[Remarks] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CategorySub2] (
[Sub2CategoryID] [int] NOT NULL ,
[SubCategoryID] [int] NULL ,
[Sub2CategoryName] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[RcatID] [int] NULL ,
[RsubID] [int] NULL ,
[Rsub2ID] [int] NULL ,
[Remarks] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
答案 0 :(得分:2)
虽然不能直接回答你的问题 - 如果你能以任何方式解决,我建议你改变架构。目前的一个令人困惑的是阅读所有不同的命名方案,更不用说它是硬编码的&限于三个级别。一个更具伸缩性的解决方案,如果您在SQL Server 2005+上运行,则使用单个自引用Category表,然后使用公用表表达式递归查询:
CREATE TABLE #Category
(
CategoryID int PRIMARY KEY IDENTITY,
ParentID int NULL,
Name nvarchar(500),
);
WITH TMP AS
(
SELECT
CategoryID,
Name,
0 AS Level
FROM
#Category
WHERE
ParentID IS NULL
UNION ALL
SELECT
C.CategoryID,
C.Name,
Level + 1 AS Level
FROM
#Category C
INNER JOIN
TMP ON TMP.CategoryID = C.ParentID
)
SELECT
CategoryID,
Name
FROM
TMP
上面几乎支持无限级别的嵌套,你将获得所有类别的ID,一个表示父行ID的ParentID,以及一个从0,1,2等开始的Level指标。