Search the value from one column in another column

2019-08-01 06:25发布

问题:

I need to search the column value from one table with column value of another table.

For example

  MyTable
    Col1 Col2
    AAA   1
    BBB   2
    CCC   3

  MyTable2
    Col1          Col2
    GHKGH AAAh      1
    dhsjsBvd        2
    bdnd CCC b      3

I need to search the col1 value from MyTable in col1 value of MyTable2.

I dont want to hard code the string but take the value from table.

Tried using instr and regex_instr, but these functions don't allow column values in the pattern to search.

I am using oracle 10g. TIA

回答1:

Tested example here: http://sqlfiddle.com/#!4/037ffe/3

select 
  t1.col1 AS t1col1, t2.col1 AS t2col1
from 
  MyTable t1

  left join MyTable2 t2
  on t2.col1 like '%' || t1.col1 || '%'

Full example including DDL:

CREATE TABLE MyTable (col1 varchar2(9));

INSERT ALL 
    INTO MyTable (col1)
         VALUES ('AAA')
    INTO MyTable (col1)
         VALUES ('BBB')
    INTO MyTable (col1)
         VALUES ('CCC')
SELECT * FROM dual;

CREATE TABLE MyTable2 (col1 varchar2(18));

INSERT ALL 
    INTO MyTable2 (col1)
         VALUES ('GHKGH AAAh')
    INTO MyTable2 (col1)
         VALUES ('dhsjsBvd')
    INTO MyTable2 (col1)
         VALUES ('bdnd CCC b')
SELECT * FROM dual;

select 
  t1.col1 AS t1col1, t2.col1 AS t2col1
from 
  MyTable t1

  left join MyTable2 t2
  on t2.col1 like '%' || t1.col1 || '%'

Resultset:

T1COL1    T2COL1
AAA       GHKGH AAAh
BBB       (null)
CCC       bdnd CCC b