[英]How do I join two tables to a first and then combine a column?
假设我在 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 列值为空,则取另一列,如果两者都不为空,则取第一列,如果两者都为空然后默认为空。 这应该给出一个这样的表:
+-------------+----------+------------+
| 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 列都应该被视为枚举。
您可以使用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
如果只是因为您可以添加一个值来代替空值,我建议使用 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
这可以使用 isnull 函数来完成。 我在这个解决方案中使用了 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.