加入通配符

时间:2019-03-22 08:26:58

标签: sql oracle

表1

|------------------------------------------------------------|
| Para_1  | column_A     | column_B        | column_C        |
--------------------------------------------------------------
| 3007576 | abc          |                 |                 |
| 3007879 | ab           |  fg             |                 |
| 3007880 | ad           |                 | x               |
| 3007900 |              |                 |                 |
|------------------------------------------------------------|

表2

|------------------------------------------------------------|
| Para_2  | column_A     | column_B        | column_C        |
--------------------------------------------------------------
| 100     | abcd         |  fgh            | xyz             |
| 200     | abc          |  fg             | z               |
| 300     | ab           |  g              | xy              |
|------------------------------------------------------------|

预期结果:

|------------------------------------------------------------|
| Para_1  | column_A     | column_B        | column_C        | Para_2
--------------------------------------------------------------
| 3007576 | abc          |                 |                 | 100
| 3007576 | abc          |                 |                 | 200
| 3007879 | ab           |  fg             |                 | 100
| 3007879 | ab           |  fg             |                 | 200
| 3007880 | ad           |                 | x               | null
| 3007900 |              |                 |                 | null
|------------------------------------------------------------|

select table1.*, table2.Para_2, table1.column_A
from table1
left outer join table2
on table2.column_A like ('%'||table1.column_A||'%') 
and table2.column_B like ('%'||table1.column_B||'%')  
and table2.column_C like ('%'||table1.column_C||'%') 

where table1.column_A is not null
and table1.column_B is not null
and table1.column_C is not null

上面的代码似乎还不够..有什么想法吗?

2 个答案:

答案 0 :(得分:0)

删除where子句是因为在示例数据的每一行中,至少有一个空列值以及3列A,B,C,因此它过滤了所有内容

<Grade MarkGrade="2" Label="GOOD" TestBins="2">2</Grade> 

答案 1 :(得分:0)

这将产生预期的结果:

select table1.*, table2.Para_2
from table1 left outer join table2
on  table2.column_A like '%'||table1.column_A||'%' 
and table2.column_B like '%'||table1.column_B||'%'
and table2.column_C like '%'||table1.column_C||'%'
and coalesce(table1.column_a, table1.column_b, table1.column_c) is not null;

如您所见,这几乎就是您所拥有的。但是不需要您的where,只需on条件的最后一行。如果您不喜欢coalesce函数,那么也可以像这样更清楚地写出额外的行:

and not (table1.column_a is null and table1.column_b is null and table1.column_c is null);

或者:

and length(table1.column_a||table1.column_b||table1.column_c)>0;