简体   繁体   English

基于非空列的MySQL内部连接

[英]MySql Inner join based on non empty columns

    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. 我必须编写一个SQL查询,该查询基于这些表上的<> 0条件在三列上具有内部联接。 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

You can use a conditional statement (case when for example) in a join clause. 您可以在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)

see SqlFiddle 参见SqlFiddle

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM