高效查询亲子关系

发布于 2024-08-11 13:49:38 字数 782 浏览 3 评论 0原文

假设您有以下数据库表:

 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 的硬依赖。

谢谢

Assuming you have the following database table:

 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

This allows the definition of hierarchical names. Each name can have one parent name, and any number of child names.

I wish to find the record corresponding to a qualified name such as "a:b:c", where colons delimit each name. I have currently done so using joins:

 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

What I'm wondering is whether there's a more efficient way to do this that does not involve denormalization of the data or taking a hard dependency on any particular DBMS.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文