Search the value from one column in another column in a different table

。_饼干妹妹 提交于 2020-01-05 06:56:30

问题


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


来源:https://stackoverflow.com/questions/14990718/search-the-value-from-one-column-in-another-column-in-a-different-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!