我有一个配置表,它包含特定用户选择的值。如果没有输入值,则应返回默认值。但有一个问题:用户属于一个特定的组,每个组都有自己的默认组。
我需要的是单个查询,它返回用户的值,如果没有找到数据,则返回他/她的组的默认值。
配置表结构非常简单:
CONFIGURATION: ConfigurationId (PK), GroupId (FK), UserId (FK), ConfigurationDetailId (FK);
CONFIGURATIONDETAIL: ConfigurationDetailId (PK), ConfigValue1, ConfigValue2
用户可能属于多个组,并且每个组具有不同的配置。这些配置被认为是不同的(具有自己的ConfigurationDetailId),即使它们的值相同。 当我查找数据时,我总是拥有GroupId和UserId
这样可行,但我想要一些更“优雅”的东西...我不喜欢的是TOP 1和ORDER BY我需要在用户特定行存在时消除默认行:
SELECT TOP 1
FROM Config C
WHERE C.GroupId = @GroupId
AND (C.UserId = @UserId OR C.UserId IS NULL)
ORDER BY C.UserId DESC
有什么想法吗?
答案 0 :(得分:3)
也许尝试自我加入,具体取决于您的表格结构。
create table config
( GroupID int,
UserID int,
ConfigId int,
ConfigValue varchar(50),
IsDefault int );
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, NULL, 1, 'A', 1);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, NULL, 2, 'B', 1);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, NULL, 3, 'C', 1);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, 1, 1, 'A1', 0);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, 1, 2, 'B1', 0);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, 1, 3, 'C1', 0);
insert into config (groupid, userid, configid, configvalue, isdefault)
values (1, 2, 1, 'A2', 0);
select
COALESCE(c1.configid, c2.configid) as configid,
COALESCE(c1.configvalue, c2.configvalue) as configvalue
from config c1 right join config c2
on (c1.groupid = c2.groupid
and c1.configid = c2.configid
and c1.isdefault = 0 and c1.userid = 2)
where c2.isdefault = 1 and c2.groupid = 1;
select
COALESCE(c1.configid, c2.configid) as configid,
COALESCE(c1.configvalue, c2.configvalue) as configvalue
from config c1 right join config c2
on (c1.groupid = c2.groupid
and c1.configid = c2.configid
and c1.isdefault = 0 and c1.userid = 1)
where c2.isdefault = 1 and c2.groupid = 1;
userid = 2的结果
CONFIGID CONFIGVALUE
1 A2
2 B
3 C
userid = 1的结果
CONFIGID CONFIGVALUE
1 A1
2 B1
3 C1
我已为此构建了SQLFiddle,因此您可以自己查看。