Search code examples
sqloracle-databasejoinregexp-like

How to display only matched items using JOIN


Can someone help me to make SQL (ORACLE) query more flexible using such conditions?

There are 2 tables:

Table 1

CodeA      Year   

1112-999   2017
1113-999   2017

Table 2

CodeB      Year   

1114-111   2017
1115-111   2018

Then run this script

SELECT aa.CodeA, bb.CodeB FROM Table 1 aa
JOIN Table 2 bb ON aa.Year = bb.Year
AND REGEXP_LIKE (aa.CodeA, '^111+2');

In this case the result is:

CodeA      CodeB   

1112-999   1114-111

But in this case it needs to show up only the 1st value and another column should be empty after running script.

For example,

CodeA      CodeB   

1112-999   NULL

But if column "CodeB" (Table 2) contains value = 1112-534, then that value should appear after running the same script

For example,

Table 1

CodeA      Year   

1112-999   2017
1113-999   2017

Table 2

CodeB      Year   

1114-111   2017
1112-534   2017
1115-111   2018

And after running the same script, the result should be:

CodeA      CodeB   

1112-999   1112-534

What should I change in this script in order to make it flexible (universal) depending on input data in table? I mean when Table 2 does not contain expected value (in this case 1112-534), then the result (for 2nd column) should be NULL:

CodeA      CodeB   

1112-999   NULL

and when Table 2 contains this value (1112-534), then the response should be:

CodeA      CodeB   

1112-999   1112-534

Here is the script I have and want to make it more flexible:

SELECT aa.CodeA, bb.CodeB FROM Table 1 aa
JOIN Table 2 bb ON aa.Year = bb.Year
AND REGEXP_LIKE (aa.CodeA, '^111+2');

Help me please))) Thanks in advance.


Solution

  • You may find it helpful to view the join results prior to filtering:

    SELECT aa.CodeA, bb.CodeB FROM Table1 aa
    JOIN Table2 bb ON aa.Year = bb.Year;
    

    Your English language specification is not quite clear, but it suggests that you want NULL filtering:

    SELECT aa.CodeA, bb.CodeB FROM Table1 aa
    JOIN Table2 bb ON aa.Year = bb.Year
    WHERE REGEXP_LIKE(aa.CodeA, '^1+2')
    and bb.CodeB is not null;
    

    See also https://en.wikipedia.org/wiki/Join_(SQL)