سؤال

Lets say that I have three tables:

1. TableA with columns TableAID (PK), Desc Nullable

2. TableB with columns TableBID (PK), TableAID(FK) Nullable

3. TableC with columns TableCID (PK), TableBID (FK) Nullable, 
   TableAID (FK) Nullable, Start_Date, End_Date

I need to return the Desc in Table A if TableC.TableBID is not null then use the TableAID(FK) in TableB to retrieve Desc else use TableAID (FK) in TableC to retrieve Desc

Note: It's possible both TableC.TableBID or TableC.TableAID can be null. In all cases I still must be able to return the other columns in TableC.

Here is my code:

Select ta.desc, tc.start_date, tc.end_date
from TableC tc
Left outer join TableB tb
on case
when tc.TableBID  is not null then (
           tc.TableBID = tb.TableBID
           Left outer join TableA ta
           on tb.TableAID = ta.TableAID 
           --my concern here is that tb.TableAID can be null. Will it still work?
)
else tc.TableAID = ta.TableAID --my concern here is that tc.TableAID can be null. 
--WIll it still work?

I'm also concern about syntax. If there is a better way to have a conditional join, please advise. I'm using oracle. This code will go into a view which will be used for a search procedure (that's why it has to return everything regardless of nulls). Thanks for your help.

هل كانت مفيدة؟

المحلول

You can put your CASE in the SELECT clause and join the tables accordingly, like this:

SELECT CASE
           WHEN tb.tableAID IS NOTNULL THEN tab.desc
           ELSE tac.desc
       END AS desc
       -- or better: NVL(tab.desc, tac.desc) AS desc
       , tc.start_date
       , tc.end_date
  FROM tableC tc
  JOIN tableB tb ON tc.tableBID = tb.tableBID
  LEFT JOIN tableA tab ON tab.tableAID = tb.tableAID
  LEFT JOIN tableA tac ON tac.tableAID = tc.tableAID
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top