0
    I have Two tables :
    Table1, Table2

I have to write a SQL query which has inner join on three columns based on <> 0 condition on these tables. My condition is

    if(table1.ID != 0), then inner join on table1.ID = table2.ID else,

    if(table1.MemberID != 0), then inner join on table1.MemberID = table2.MemberID else,

    inner join on table1.PersonID = table2.PersonID
4
  • you sure that you need inner join here? left join can handle situations where you have non existent values Commented Nov 27, 2013 at 8:22
  • @Goran Stuc : Yes I need inner join in this case. I have to match both the fields. Commented Nov 27, 2013 at 8:23
  • why dont you use join with OR for each conditions Commented Nov 27, 2013 at 8:28
  • @timus I dont know how to use OR condition. It would be great if you could help me write one query for above and post it. Commented Nov 27, 2013 at 8:30

2 Answers 2

1

You can use a conditional statement (case when for example) in a join clause.

select t1.*, t2.*
from table1 t1
inner join table2 t2 on 
            (case when 
                 t1.ID != 0 
                 then t1.ID =t2.Id
                 else
                 case when t1.MemberId !=0 
                      then t1.MemberId = t2.MemberId
                      else
                           t1.PersonId = t2.PersonId
                  end
            end)

see SqlFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

This should work.

select * 
from Table1, Table2
where table1.Personid = table2.personId
and (((Table1.id != 0) and  (Table1.id = table2.Id))
or ((Table1.memberid != 0) and (Table1.memberid = table2.memberId)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.