有效地查询亲子关系

时间:2009-11-11 14:44:59

标签: sql parent-child relationships

假设您有以下数据库表:

 create table Names (
  Id INT IDENTITY NOT NULL,
    Name NVARCHAR(100) not null,
    ParentNameId INT null,
    primary key (Id)
 )

 create index IX_Name on Names (Name)

 alter table Names
  add constraint FK_NameNames
  foreign key (ParentNameId) 
  references Names

这允许定义分层名称。每个名称可以有一个父名称和任意数量的子名称。

我希望找到与限定名称相对应的记录,例如“a:b:c”,其中冒号分隔每个名称。我目前使用连接这样做:

 select
  Id
 from
  Names names0
  inner join Names names1 on names0.ParentNameId = names1.Id
  inner join Names names2 on names1.ParentNameId = names2.Id
 where
  names0.Name = 'a' and
  names1.Name = 'b' and
  names2.Name = 'c' and
  names0.ParentNameId is null

我想知道的是,是否有更有效的方法来实现这一点,不涉及数据的非规范化或对任何特定的DBMS采取硬依赖。

由于

1 个答案:

答案 0 :(得分:1)

您可能希望阅读此内容:http://www.developersdex.com/gurus/articles/112.asp

相关问题