【问题标题】:Define join condition定义连接条件
【发布时间】:2018-06-19 14:32:29
【问题描述】:

我有两个表 tab1 和 code_list(见下文)。 Tab1 是一个大表(数百万条记录),code_list 使用左连接连接到 tab1。

create table tab1 (
key1 varchar2(10)
, key2 varchar2(10)
)
;

insert into tab1 values ('_10', '__1');
insert into tab1 values ('_10', '__2');
insert into tab1 values ('_10', '__3');
insert into tab1 values ('_10', '_99');
insert into tab1 values ('_10', null);
insert into tab1 values ('_20', '__1');
insert into tab1 values ('_20', '__2');
insert into tab1 values ('_20', '__3');
insert into tab1 values ('_20', '_99');
insert into tab1 values ('_20', null);
commit;

create table code_list (
key1 varchar2(10)
, key2 varchar2(10)
, value varchar2(10)
)
;

insert into code_list values ('_10', '__1', 'value1');
insert into code_list values ('_10', '__2', 'value2');
insert into code_list values ('_10', '__3', 'value3');
insert into code_list values ('_10', null, 'value4');
insert into code_list values ('_20', '__1', 'value1');
insert into code_list values ('_20', '__2', 'value2');
insert into code_list values ('_20', '__3', 'value3');
insert into code_list values ('_20', null, 'value5');
commit;

我正在尝试创建连接两个表的 SQL 语句,如下所示:

  • 基于 key1 列加入

  • 基于 key2 列加入

  • 如果 tab1 中的 key2 为 null,则连接到 code_list 表中 key2 列中的 null 值
  • 如果 tab1 的 key2 列的值在 code_list 表的 key2 列中不存在,则连接到 code_list 中 key2 列的值为 NULL 的行

到目前为止,我有以下声明:

select t1.*
, t2.value
from tab1 t1
left join code_list t2 on t1.key1 = t2.key1 
and (nvl(t1.key2, 'x') = nvl(t2.key2, 'x'))
;

它工作正常,但它不反映上述条件的最后一个(如果 tab1 的 key2 列中的值在 code_list 表的 key2 列中不存在,则连接到 code_list 中 key2 列中的值为 NULL 的行) .

结果如下:

_10 __1 value1
_10 __2 value2
_10 __3 value3
_10 (null) value4
_20 __1 value1
_20 __2 value2
_20 __3 value3
_20 (null) value5
_10 _99 (null) 
_20 _99 (null) 

但我希望它给出以下结果:

_10 __1 value1
_10 __2 value2
_10 __3 value3
_10 (null) value4
_20 __1 value1
_20 __2 value2
_20 __3 value3
_20 (null) value5
_10 _99 value4 
_20 _99 value5 

最后两行不同。

感谢您的帮助。

【问题讨论】:

  • _10 __1 value1 怎么了?你的结果没有意义。是什么规则过滤掉的?
  • 你是对的,对不起,我在编辑我的帖子时错过了那一行。现在好了。

标签: sql oracle


【解决方案1】:
select t1.*, nvl(t2.value,t3.value) value
from   tab1 t1 
         left join code_list t2 
           on  t1.key1 = t2.key1 
           and (nvl(t1.key2, 'x') = nvl(t2.key2, 'x'))
         left join code_list t3 
           on  t1.key1 = t3.key1 
           and t3.key2 is null

不要忘记为大表tab1的连接条件创建函数索引:(key1,nvl(key2,'x'))

【讨论】:

    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2016-07-24
    • 2011-07-02
    • 2011-02-19
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多