合并两个左联接上的列

时间:2019-01-08 03:18:19

标签: sql postgresql

我有3张桌子,如下所示:

Video
+----+--------+-----------+
| id |  name  | videoSize |
+----+--------+-----------+
|  1 | video1 | 1MB       |
|  2 | video2 | 2MB       |
|  3 | video3 | 3MB       |
+----+--------+-----------+

Survey
+----+---------+-----------+
| id |  name   | questions |
+----+---------+-----------+
|  1 | survey1 |         1 |
|  2 | survey2 |         2 |
|  3 | survey3 |         3 |
+----+---------+-----------+

Sequence
+----+---------+-----------+----------+
| id | videoId | surveyId  | sequence |
+----+---------+-----------+----------+
|  1 | null    | 1         |        1 |
|  2 | 2       | null      |        2 |
|  3 | null    | 3         |        3 |
+----+---------+-----------+----------+

我想查询Sequence并在视频表和调查表上联接,并合并公共列,而无需指定列名(在这种情况下为name),如下所示:

Query Result:
+----+---------+-----------+----------+---------+-----------+-----------+
| id | videoId | surveyId  | sequence |  name   | videoSize | questions |
+----+---------+-----------+----------+---------+-----------+-----------+
|  1 | null    | 1         |        1 | survey1 | null      | 1         |
|  2 | 2       | null      |        2 | video2  | 2MB       | null      |
|  3 | null    | 3         |        3 | survey3 | null      | 3         |
+----+---------+-----------+----------+---------+-----------+-----------+

这可能吗?

顺便说一句,下面的sql不起作用,因为它没有在name字段上合并:

SELECT * FROM "Sequence"
LEFT JOIN "Survey" ON "Survey"."id" = "Sequence"."surveyId"
LEFT JOIN "Video" ON "Video"."id" = "Sequence"."videoId"

1 个答案:

答案 0 :(得分:1)

此查询将显示您想要的内容:

select
  s.*,
  coalesce(y.name, v.name) as name, -- picks the right column
  v.videoSize,
  y.questions
from sequence s
left join survey y on y.id = s.surveyId
left join video v on v.id = s.videoId

但是,SQL标准要求您命名所需的列。唯一的例外是*,如上所示。