sqloracle-database

PL_SQL hard for me join - dynamic ID-s in second table


I tried to resolve this but I have no idea how to do it.

I have two tables, TABLE_S and TABLE_G. In TABLE_S I have an ID and in TABLE_G, I have two: ID1 and ID2.

TABLE_S     ID
TABLE_G     ID1    ID2

I want a left join, if there's no result for TABLE_G_ID1, then left join TABLE_G_ID2

Something like this:

SELECT * 
FROM TABLE_S
LEFT JOIN TABLE_G ON TABLE_S.ID = TABLE_G.ID1 
                  -- if no result then: ON TABLE_S.ID = TABLE_G.ID2

I tried this:

Oracle try second condition only if first one gave nothing in join

But it doesn't work for me, and there is full join, not left join.

Appreciate your suggestion!


Solution

  • Use AND and OR:

    SELECT *
    FROM   TABLE_S s
           LEFT OUTER JOIN TABLE_G g
           ON (  s.ID = g.ID1
              OR (
                     (s.ID <> g.ID1 OR s.ID IS NULL OR g.ID1 IS NULL)
                 AND s.ID = g.ID2
                 )
              );
    

    (Which is exactly the same logic as the question you link.)

    or use a CASE expression:

    SELECT *
    FROM   TABLE_S s
           LEFT OUTER JOIN TABLE_G g
           ON s.ID = CASE s.ID WHEN g.ID1 THEN g.ID1 ELSE g.ID2 END;
    

    (Which is shorter to type but you may find that the SQL engine has difficulty using indexes on the columns due to them being inside the CASE expression.)