用于搜索越来越高级别的SQL冒泡或分层模式
我们有公司、分支机构和用户表/级别。每个级别都有一个与配置表中的配置关联的可空id。如果配置id为null,则它应返回更高级别的配置,并且存在与该更高级别关联的不可为null的id。如果在最高级别没有关联的配置,那么它应该不返回任何内容。另一个复杂性是,配置的IsDeleted值应为0 对于这样的层次结构,什么是好的SQL模式?我确实在网上搜索过这个,但因为我甚至不知道该怎么称呼它,所以没有得到任何有用的结果 我在这里尝试了sql FIDLE:,但我不喜欢我使用的模式。模式只是一组表,每个表都有一个元素,公司是唯一指向配置的公司。 模式: 以下是查询:用于搜索越来越高级别的SQL冒泡或分层模式,sql,hierarchy,Sql,Hierarchy,我们有公司、分支机构和用户表/级别。每个级别都有一个与配置表中的配置关联的可空id。如果配置id为null,则它应返回更高级别的配置,并且存在与该更高级别关联的不可为null的id。如果在最高级别没有关联的配置,那么它应该不返回任何内容。另一个复杂性是,配置的IsDeleted值应为0 对于这样的层次结构,什么是好的SQL模式?我确实在网上搜索过这个,但因为我甚至不知道该怎么称呼它,所以没有得到任何有用的结果 我在这里尝试了sql FIDLE:,但我不喜欢我使用的模式。模式只是一组表,每个表都有
declare @UserID int
select @UserID = 1
declare @uconfigID int
declare @bconfigID int
declare @cconfigID int
declare @numConfigs int
select @numConfigs = 0 -- UPDATE (makes query work)
SELECT @uconfigID = au.configID, @bconfigID = b.configID, @cconfigID = c.configID
from all_user au
join branch b on au.branchID = b.ID
join company c on b.companyID = c.ID
where au.ID = @UserID
if @uconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @uconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @uconfigID
and IsDeleted = 0
END
END
if @numConfigs = 0 and @bconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @bconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @bconfigID
and IsDeleted = 0
END
END
if @numConfigs = 0 and @cconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @cconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @cconfigID
and IsDeleted = 0
END
END
另外,我不喜欢使用联接,因为我真的希望在第一级对它进行短路,以返回有效(非删除)配置
有更好的方法吗?也许是递归的
谢谢
declare @UserID int
select @UserID = 1
declare @uconfigID int
declare @bconfigID int
declare @cconfigID int
declare @numConfigs int
select @numConfigs = 0 -- UPDATE (makes query work)
SELECT @uconfigID = au.configID, @bconfigID = b.configID, @cconfigID = c.configID
from all_user au
join branch b on au.branchID = b.ID
join company c on b.companyID = c.ID
where au.ID = @UserID
if @uconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @uconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @uconfigID
and IsDeleted = 0
END
END
if @numConfigs = 0 and @bconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @bconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @bconfigID
and IsDeleted = 0
END
END
if @numConfigs = 0 and @cconfigID is not null
BEGIN
select @numConfigs = count(*)
from config
where id = @cconfigID
and IsDeleted = 0
if @numConfigs = 1
BEGIN
select *
from config
where id = @cconfigID
and IsDeleted = 0
END
END