如何将两个表连接到第一个表,然后合并一个列?

时间:2020-01-15 00:09:35

标签: sql database postgresql join left-join

比方说,我在PostgreSQL数据库中有三个表。 films

+-------------+----------+
|    film     | theme_id |
+-------------+----------+
| film name 1 |      23  |
| film name 2 |      56  |
| film name 3 |      11  |
| film name 4 |      12  |
+-------------+----------+

themes_old

+----------+------------+
| theme_id | streams_on |
+----------+------------+
|       23 | Spotify    |
|       56 | Tidal      |
+----------+------------+

和一个themes_new

+----------+------------+
| theme_id | streams_on |
+----------+------------+
|       11 | Spotify    |
|       56 | Tidal      |
+----------+------------+

我想将第二个表和第三个表都连接到第一个表,但不要重复使用streams_on列。例如。如果我运行

SELECT * 
FROM films as f 
LEFT JOIN themes_old as to ON f.theme_id=to.theme_id 
LEFT JOIN themes_new as tn on f.theme_id=tn.theme_id

我会得到

+-------------+----------+------------+------------+
|    film     | theme_id | streams_on | streams_on |
+-------------+----------+------------+------------+
| film name 1 |       23 | Spotify    | [null]     |
| film name 2 |       56 | Tidal      | Tidal      |
| film name 3 |       11 | [null]     | Spotify    |
| film name 4 |       12 | [null]     | [null]     |
+-------------+----------+------------+------------+

但是我想合并最后两列,这样就只有一个streams_on列,以便对于任何一行,如果一个streams_on列的值为null,则取另一列,如果两者都不为null,则取第一列,如果两者均为null,然后默认为null。这应该给出一个这样的表:

+-------------+----------+------------+
|    film     | theme_id | streams_on |
+-------------+----------+------------+
| film name 1 |       23 | Spotify    |
| film name 2 |       56 | Tidal      |
| film name 3 |       11 | Spotify    |
| film name 4 |       12 | [null]     |
+-------------+----------+------------+

我觉得这是一份自我加入的工作,但我无法通过搜索找到很多东西。有任何想法吗?顺便说一下,应该将streams_on列都视为枚举。

3 个答案:

答案 0 :(得分:2)

您可以使用COALESCE合并两个列值:

SELECT f.film, f.theme_id, COALESCE(to.streams_on, tn.streams_on) AS streams_on
FROM films as f 
LEFT JOIN themes_old as to on f.theme_id=to.theme_id 
LEFT JOIN themes_new as tn on f.theme_id=tn.theme_id

如果您想将“新”流优先于“旧”流,只需更改COALESCE中值的顺序即可,即

COALESCE(tn.streams_on, to.streams_on) AS streams_on

答案 1 :(得分:0)

如果仅因为您可以添加一个值以代替空值而出现,我建议您使用Case语句。可以更轻松地将信息快速导出到报告中

SELECT 
theme_id,
CASE
WHEN themes_new.streams_on IS NOT NULL THEN themes_new.streams_on
WHEN (themes_new.streams_on IS NULL AND themes_old.streams_on IS NULL) THEN "None"
ELSE themes_old.streams_on

FROM films as f
LEFT JOIN themes_old as to on f.theme_id=to.theme_id 
LEFT JOIN themes_new as tn on f.theme_id=tn.theme_id

答案 2 :(得分:0)

这可以通过使用isull函数来完成。我将SQLserver用于此解决方案。 如果不使用旧主题,它将检查新表中可用的主题。 让我知道这是否对您有帮助。

select  f.film_name, 
    isnull(new.theme_id,old.theme_id), 
    isnull(new.streams_on, old.streams_on) 
    from films f 
            left join themes_old old 
                on f.theme_id = old.theme_id 
            left join themes_new new 
                on f.theme_id = new.theme_id