Is it possible in SQL to match a LIKE from a list of records in a subquery?
-
09-09-2019 - |
Question
Using these tables, as a sample:
CodeVariations:
CODE
-----------
ABC_012
DEF_024
JKLX048
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.
Solution
Does this do what you need?
select distinct RC.* from RegisteredCodes RC, CodeVariations CV
where RC.CODE LIKE CV.CODE;
OTHER TIPS
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?
select * from CAT_ITEM where DESCRICAO LIKE '%TUBO%%PVC%%DNR%'
All like list is in a string.
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) ;