views:

1368

answers:

4

Using these tables, as a sample:

Table CodeVariations

CODE
-----------
ABC_012
DEF_024
JKLX048

And table RegisteredCodes

CODE       AMOUNT
--------   ------
ABCM012         5
ABCK012        25
JKLM048        16

Is it possible to write a query to retrieve all rows in RegisteredCodes when CODE matches a pattern in any row of the CodeVariations table? That is, any row that matches a LIKE pattern of either 'ABC_012', 'DEF_024' or 'JKLX048'

Result should be

CODE       AMOUNT
--------   ------
ABCM012         5
ABCK012        25

I'm using PostgreSQL, but it would be interesting to know if it's possible to do this in a simple query for either PostgreSQL or any other DB.

+3  A: 

Does this do what you need?

select distinct RC.* from RegisteredCodes RC, CodeVariations CV
where RC.CODE LIKE CV.CODE;
davogones
It needs to be a SELECT DISTINCT if you want to allow the situation where a CODE could be LIKE more than one of the CODEVARIATIONS.CODEThat doesn't happen in the data as given, but there are possible code variations where it could.
Walter Mitty
You're right, I'll update it. Thanks.
davogones
A: 

Is this you are looking for:

SELCET * FROM RegisteredCodes RC WHERE RC.Code IN (SELECT CODE FROM CodeVariations WHERE CODE LIKE ('ABC%') AND CODE LIKE ('%012')

This will fetch all the record that start with 'ABC' and Ends with '012' and similar for 'DEF" and 'JKL'.
OR

Are you looking for something like this?

Sachin Gaur
A: 

In Oracle & PostgreSQL you can you single char wildcards "_" for single chars.

select RC.* from RegisteredCodes RC, CodeVariations CV
where RC.CODE LIKE 'ABC_012';

use Substring

select RC.* from RegisteredCodes RC, CodeVariations CV
where RC.CODE LIKE substring(CV.Code,1,3)||'_'||substring(CV.Code,5) ;
Dheer
A: 

select * from CAT_ITEM where DESCRICAO LIKE '%TUBO%%PVC%%DNR%'

All like list is in a string.