SQL条件连接,带默认值

时间:2018-09-26 14:21:51

标签: sql postgresql

我对此查询有点挣扎,我有下表:

setting
-------
id  | name   | value   | type
--------------------------------
1   | title  | Hi      | string
2   | color  | #ff0000 | string

user_setting
-------
id | userId | settingId | value
--------------------------------
1  | 1      | 1         | Hello

user
-------
id | email
1  | foo@test.com

我想运行一个查询,该查询将为用户1选择所有设置,但还包括默认值,因此理想情况下,我得到以下信息:

id    | default | value
-----------------------
title | Hi      | Hello
color | #ff0000 | null

我当前的查询是

SELECT  setting.id, setting.name, setting.value,  user_setting.value, user.id
FROM setting
RIGHT JOIN user_setting
    ON setting.id = "user_setting"."settingId"
LEFT OUTER JOIN user
    ON "user_setting"."userId" = user.id
WHERE user.id = 1

但这只会给我用户定义的值。

编辑:更新了设置表

1 个答案:

答案 0 :(得分:4)

我认为您想要一个setting_id。但我认为您的设置缺少setting ------- id | name | value | type -------------------------------- 1 | title | Hi | string 2 | color | #ff0000 | string 的一列(或任何它所谓的名称)。因此,该表应为:

user_settings.setting_id

否则select s.name, s.value as default, us.value from setting s left join user_setting us on us.setting_id = s.id and us.user_id = 1 不会引用任何内容。使用此列,您需要:

 const options: CameraOptions = {
    quality: 10
    , destinationType: this.camera.DestinationType.DATA_URL
    , mediaType: this.camera.MediaType.PICTURE // Try this
    , sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
 };