我有几张桌子。一个包含组的表:
[ID] - [ParentGroupID]
1 - NULL
2 1
3 1
4 2
另一个有设置
[Setting] - [GroupId] - [Value]
Title 1 Hello
Title 2 World
如果我查询第3组的标题,我现在想要“你好” 如果我查询第4组的标题(而不是“Hello”),我想回到“世界”
有没有办法在MSSQL中有效地执行此操作?目前我正在代码中递归地解决这个问题。但是我希望SQL可以为我解决这个问题。
答案 0 :(得分:2)
SELECT settings.value
FROM settings
JOIN groups ON settings.groupid = groups.parentgroupid
WHERE settings.setting = 'Title'
AND groups.id = 3
答案 1 :(得分:1)
这是我们公司多次遇到的问题。这适用于任何情况,包括何时只能在某些级别而不是其他级别设置设置(请参阅SQL小提琴http://sqlfiddle.com/#!3/16af0/1/0:
With GroupSettings(group_id, parent_group_id, value, current_level)
As
(
Select g.id as group_id, g.parent_id, s.value, 0 As current_Level
From Groups As g
Join Settings As s On s.group_id = g.id
Where g.parent_id Is Null
Union All
Select g.id, g.parent_id, Coalesce((Select value From Settings s Where s.group_id=g.id), gs.value), current_level+1
From GroupSettings as gs
Join Groups As g On g.parent_id = gs.group_id
)
Select *
From GroupSettings
Where group_id=4
答案 2 :(得分:0)
我相信以下是您所寻求的。请参阅sqlfiddle
SELECT vALUE FROM
Groups g inner join Settings s
ON g.ParentGroupId = s.GroupID
WHERE g.ID = 3 -- will return Hello,], set ID = 4 will return World