高效查询亲子关系
假设您有以下数据库表:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想阅读以下内容: http://www.developersdex.com/gurus/articles /112.asp
You might like to read this: http://www.developersdex.com/gurus/articles/112.asp