简体   繁体   中英

Alternative to REGEXP_LIKE in oracle

Can you please tell me if there is any alternative function which I can use for REGEXP_LIKE ?

I have the following situation:

Names:
ID NAME
1  Alex
2  Jim
3  Tom

Invoices:
ID Amount Name_IDs
1  100    1;2;
2  200    2;3;

Wanted output:
Invoice_ID Names     Amount:
1          Alex;Jim; 100
2          Jim;Tom;  200

I know that the database model is not quite technically right, but now I'm using a query for this with REGEXP_LIKE to add in a listagg() the names, but the performance is very very slow.

SELECT inv.id as invoice_id, 
       SELECT listagg(n.name,';') WITHIN GROUP (ORDER BY NULL) from names where REGEXP_LIKE(inv.names, '(^|\W)' || n.name || '(\W|$) 'as names
       inv.amount as amount
from invoices inv;

Can you please give me any idea how to improve this query ?

Thank you!

If you have an index on your names table then this should be faster:

select i.id,
       i.amount,
       (select listagg(n.name, ';') within group(order by null)
          from (select trim(regexp_substr(str, '[^;]+', 1, level)) ASPLIT
                  from (select i.name_ids as str from dual)
                connect by regexp_substr(str, '[^;]+', 1, level) is not null) t
          join names n
            on n.id = t.asplit)
  from invoices i;

ie first split by Name_IDs and join with the names table.

I suggest that you change your data model to something like the following:

NAMES:
ID_NAMES NAME
10       Alex
20       Jim
30       Tom

INVOICES:
ID_INVOICE Amount
1          100
2          200

INVOICE_NAMES:
ID_INVOICE  ID_NAME
1           10
1           20
2           20
2           30

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM