Domanda

I am facing a strange scenario where I need to match an integer with varchar containing digits separated by commas in oracle

Example:

Table t1:

id integer
key integer

Table t2

id integer,
keys varchar2

T1 values are:

1,111
2,201
3,301

T2 values are:

1, "111,301"
2, "111,201"
3, "201,301"

PROBLEM: Is there any way I can match or regular_expression match with key of T1 with keys of T2?

È stato utile?

Soluzione

you can do a regular join without regex for this:

select *
  from t1
       inner join t2
               on ','||t2.keys||',' like '%,'||to_char(t1.key)||',%';

eg:

SQL> create table t1(id, key)
  2  as
  3  select 1, 111 from dual union all
  4  select 2, 201 from dual union all
  5  select 3, 301 from dual;

Table created.

SQL> create table t2(id, keys)
  2  as
  3  select 1, '111,301' from dual union all
  4  select 2, '111,201' from dual union all
  5  select 3, '201,301' from dual;

Table created.

SQL> select *
  2    from t1
  3         inner join t2
  4                 on ','||t2.keys||',' like '%,'||to_char(t1.key)||',%';

        ID        KEY         ID KEYS
---------- ---------- ---------- -------
         1        111          1 111,301
         1        111          2 111,201
         2        201          2 111,201
         2        201          3 201,301
         3        301          1 111,301
         3        301          3 201,301

6 rows selected.

It's not regex, just concatenation. For example lets say we wanted to compare

KEY    KEYS
111    111,301

we could say

where keys like '%'||key||'%'

i.e. expanded, this is

where '111,301' like '%111%'

which matches fine. But I added some commas there too. ie I did this:

where ',111,301,' like '%,111,%'

Why? imagine instead you had this data:

KEY    KEYS
111    1111,301

If we did the simple join:

where '1111,301' like '%111%'

it would incorrectly match. By injecting leading and trailing commas on both sides:

where ',1111,301,' like '%,111,%'

is no longer erroneously matches, as ,1111, isn't like ,111,.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top