0

In my oracle database i have 2 tables and i have to join them where in TABLE A i have column ID which is number, and TABLE B where i have column SCIDS which is varchar2. Here is some example:

TABLEA.ID | TABLEB.SCIDS
162       | 162,163
162       | 555,162,33
161       | 161

Some sql i tried

select A.ID
from TABLEA A
    left JOIN TABLEB B 
where "," || S.ID in "," || B.SCIDS

This does not work it return only the records that are not "array" in SCIDS e.g 3rd record 161.

How to return all ?

jarlh
  • 42,561
  • 8
  • 45
  • 63
xMilos
  • 1,519
  • 4
  • 21
  • 36

2 Answers2

2

You could try this, though not completely efficient one

with dist_tablea
     AS (SELECT DISTINCT ID
           FROM TABLEA)

SELECT a.ID, B.SCIDS
  FROM dist_tablea a LEFT JOIN TABLEB b ON REGEXP_LIKE (b.SCIDS, '(^|,)'||a.id||'(,|$)')

Output:

    ID  SCIDS
-------  -------
    161 161
    162 162,163
    162 555,162,33
Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45
1

Concatenate commas before and after both fields and then use the LIKE operator:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TABLEA( ID ) AS
  SELECT 161 FROM DUAL UNION ALL
  SELECT 162 FROM DUAL;

CREATE TABLE TABLEB( SCIDS ) AS
  SELECT '162,163' FROM DUAL UNION ALL
  SELECT '555,162,33' FROM DUAL UNION ALL
  SELECT '161' FROM DUAL;

Query 1:

SELECT *
FROM   TABLEA A
       LEFT OUTER JOIN TABLEB B
       ON ( ',' || B.SCIDS || ',' LIKE '%,' || A.ID || ',%' )

Results:

|  ID |      SCIDS |
|-----|------------|
| 161 |        161 |
| 162 |    162,163 |
| 162 | 555,162,33 |

Also:

  • When you use a LEFT [OUTER] JOIN you need to specify the join condition in the ON clause.
  • String literals are surrounded by ' single quotes. Double quotes are used (primarily) to enforce case-sensitivity on object identifiers (i.e. column names).
MT0
  • 143,790
  • 11
  • 59
  • 117