如果用户设置表为空,则从默认表中为用户选择默认设置

时间:2016-02-23 00:11:21

标签: sql-server

我的sql很弱,我很难得到我想要的结果,我相信这很简单。

我有三张桌子:

user, usersetting and defaultsetting

用户表格列:

UserId | Email

UserSetting表列:

UserId | SettingKey | IsEnabled

DefaultSetting表列:

SettingKey | IsEnabled

如果用户明确更新了他们的设置,用户将只在usersetting表中有一条记录,否则他们应该从defaultSetting表中获取该设置。用户的开启或关闭设置(IsEnabled)

我想编写一个查询,以获取启用了设置X(settingKey = x)的所有用户。如果用户在其UserSettings表中没有用于设置x但是默认设置IsEnabled = true的行,那么我仍然希望为该用户获取一行。

所以逻辑上我想这样做

Select UserId, Email from User if they have turned setting x on explicitly or setting x defaults to on

2 个答案:

答案 0 :(得分:0)

coalesce是你的朋友。

Select UserId, Email, coalesce(UserSetting.SettingKey, DefaultSetting.SettingKey) as SettingKey
from User 
left join UserSetting 
on user.userid = UserSetting.userid
left join DefaultSetting 
on UserSetting.SettingKey = DefaultSetting.SettingKey

答案 1 :(得分:0)

这应该有效。我包括了样本表和测试数据

create table #Users (UserId int, Email varchar(100))
create table #UserSetting (UserId int, SettingKey varchar(10), IsEnabled int)
create table #DefaultSetting (SettingKey varchar(10), IsEnabled int)

insert into #Users values (1, 'User1')
insert into #Users values (2, 'User2')
insert into #Users values (3, 'User3')

insert into #DefaultSetting values ('default', 1)

insert into #UserSetting values (1, 'pass1', 1)
insert into #UserSetting values (2, 'pass2', 1)


select u.UserId, u.Email, coalesce(us.SettingKey, ds.SettingKey) SettingKey
from #Users u
    left join #UserSetting us on us.UserId = u.UserId and us.IsEnabled = 1
    cross join #DefaultSetting ds
where coalesce(us.SettingKey, ds.SettingKey) = 'pass2'