【问题标题】:full outer join in redshift红移中的完全外连接
【发布时间】:2022-01-16 22:34:04
【问题描述】:

我有 2 个表 A 和 B 的列,包含学生的一些详细信息(所有列都是整数):
答:
st_id,
st_subject_id,

乙:
st_id,
st_subject_id,
st_count1,
st_count2

st_id 是学生编号,st_subject_id 是科目编号。
对于学生 id 15,有以下条目:
答:
15 | 1
15 | 2
15 | 3

乙:
15 | 1 | 31 | 11
15 | 2 | 30 | 14
15 | 4 | 21 | 6
15 | 5 | 26 | 9

A表3个科目,B表4个科目(2个与A表匹配,2个额外)。

我想将最终结果显示为:
15 | 1 | 31 | 11
15 | 2 | 30 | 14
15 | 3 |空 |空
15 | 4 | 21 | 6
15 | 5 | 26 | 9

这可以使用 SQL 中的完全外连接来完成,还是通过其他方法来完成?

【问题讨论】:

  • 外部连接会很好 - 是什么阻止了你?
  • @Bashton 在编写完整的外连接时,我们需要在选择中给出列名。但是对于某些条目,我需要包括表 A 中的 st_id、st_subject_id ,有时还包括 B 中的。我应该如何在 select 语句中传递这些列?你能写一个示例查询吗?这真的很有帮助。

标签: sql amazon-redshift outer-join


【解决方案1】:

我认为这样的事情就足够了,但我现在无法测试。 合并意味着将从两个表中选择第一个非空值。

select
coalesce(A.st_id, B.st_id) st_id,
coalesce(A.st_subject_id, B.st_subject_id) st_subject_id,
B.st_count1,
B.st_count2

from A

full outer join B
on A.st_id = B.st_id and A.st_subject_id = B.st_subject_id

【讨论】:

  • 非常感谢@Bashton!使用合并完全解决了我的问题。
  • 别担心!很高兴它有帮助:)
猜你喜欢
  • 2010-09-20
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2013-03-11
  • 2022-01-01
相关资源
最近更新 更多