MySql内连接基于非空列

时间:2013-11-27 08:18:15

标签: mysql sql

    I have Two tables :
    Table1, Table2

我必须编写一个SQL查询,它基于三列具有内连接 on<> 0条件 在这些桌子上。 我的病情是

    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

2 个答案:

答案 0 :(得分:1)

您可以在join子句中使用条件语句(例如,大小写)。

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)

请参阅SqlFiddle

答案 1 :(得分:0)

这应该有效。

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)))