简单连接表为每一行分配默认值(包括sql小提琴)

时间:2017-11-16 17:16:13

标签: sql postgresql

我确信这个问题有一个非常简单的答案,但我很难找到它。

我有一个包含属于用户的设置的表。

| user_id | setting  | value  |     
-------------------------------     
| 1       | paying?  | true   |     
| 2       | paying?  | false  |     
| 2       | demo?    | true   |     
| 2       | active?  | true   |

我还有一个默认设置的表格,以防特定用户的设置不存在。

| setting  | value  |
---------------------
| paying?  | true   |
| demo?    | true   |
| active?  | false  |
| hidden?  | false  |

我需要做的是返回每个用户的所有设置(仅当没有为该用户分配时使用默认设置):

| user_id | category | value  |
-------------------------------
| 1       | paying?  | true   |
| 1       | demo?    | true   |
| 1       | active?  | false  |
| 1       | hidden?  | false  |
| 2       | paying?  | false  |
| 2       | demo?    | true   |
| 2       | active?  | true   |
| 2       | hidden?  | false  |

此联接不会返回每个用户的结果。我做错了什么?

SELECT u.user_id, COALESCE(u.category, g.category) as category, COALESCE(u.value, g.value) as value
FROM user_settings as u
FULL OUTER JOIN global_settings as g on u.category = g.category
ORDER BY u.user_id, u.category

SQLFiddle here

1 个答案:

答案 0 :(得分:2)

使用global_settings交叉加入不同的用户,并将user_settings表加入到此处。

SELECT u.user_id, COALESCE(us.category, g.category) as category,
COALESCE(us.value, g.value) as value
FROM (select distinct user_id from user_settings) as u
cross join global_settings g
left join user_settings as us on us.category = g.category and us.user_id=u.user_id
order by 1,2