【问题标题】:Left outer join for the same table works wrong on redshift同一张表的左外连接在红移上工作错误
【发布时间】:2015-11-12 14:10:14
【问题描述】:

我需要在同一张表上执行左外连接。因此,我希望表 1 中的所有请求列,并且只有表 2 中加入的列。

复制方法如下:

drop table nz_mri_survey_agg;

create table mri_survey_agg (
HOUSEHOLD_PERSON_HK integer,
MRI_DICTIONARY_ID   INTEGER,
rank integer);

insert into mri_survey_agg values (651694412, 2127115057, 36903);
insert into mri_survey_agg values (647638311, 1293574238, 35413);
insert into mri_survey_agg values (647638311, -2076426274, 35413);
insert into mri_survey_agg values (651694412, -2076426274, 35413);
insert into mri_survey_agg values (651694412, -2051582071, 35411);
insert into mri_survey_agg values (647638311, -1747375415, 35613);
insert into mri_survey_agg values (647638311, 1234567, 35610);

这里是查询:

select distinct t1.household_person_hk, t2.mri_dictionary_id 
from mri_survey_agg t1 
left outer join (
    select household_person_hk, mri_dictionary_id from mri_survey_agg 
    where mri_dictionary_id in 
    (-2076426274, -2051582071, -1747375415)) t2 
on t1.household_person_hk = t2.household_person_hk;

我期待下一个输出:

household_person_hk mri_dictionary_id
651694412           -2051582071
647638311           -2076426274
651694412           -2076426274
647638311           -1747375415
647638311            <NaN>

输出是:

household_person_hk mri_dictionary_id
651694412           -2051582071
647638311           -2076426274
651694412           -2076426274
647638311           -1747375415

它在 Postgres 上运行完美,但在 Redshift 上没有给我预期的结果。

感谢任何提示。

UPD:其实实际输出是正确的!

【问题讨论】:

  • 您的实际输出在我看来是正确的。你能解释一下为什么当你也得到一个非空值的647638311 时你期望得到一个空值的647638311 吗?你不需要指定mri_dictionary_id in (-2076426274, -2051582071, -1747375415) or mri_dictionary_id is null吗?
  • 你是对的,因为 distinct 不会给出 NULL 的 647638311。起初这让我很困惑,但现在没关系。
  • 不,它与 DISTINCT 没有任何关系。这就是 OUTER JOIN 的工作原理。获得我提到的预期结果的唯一方法是,如果您将 or mri_dictionary_id is null 添加到内部查询并且内部查询中的表有 (647638311, NULL) 的记录。

标签: sql left-join amazon-redshift


【解决方案1】:

我刚刚在 Postgres 上运行了您的代码,它返回了四行,这是正确的。 Here 是一个 SQL Fiddle,现在可以使用了。

请注意,您的查询可以更容易地写成:

select distinct t1.household_person_hk, t2.mri_dictionary_id 
from mri_survey_agg t1 left outer join
     mri_survey_agg t2
     on t1.household_person_hk = t2.household_person_hk and
        t2.mri_dictionary_id in (-2076426274, -2051582071, -1747375415);

【讨论】:

  • @Alex 。 . .一个非常相似的版本,修正了拼写错误(现在有正确的版本)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-10-26
相关资源
最近更新 更多