加入不同条件的不同表格

时间:2016-07-30 14:54:07

标签: mysql sql

我的桌子

Renovationinfo

BlockCode|arsehRow|SakhtemanRow
-------------------------------
1        |1       |00          
2        |2       |00          
3        |3       |01          

ArsehMalk

BlockCode|arsehRow|name
------------------------
1        |1       |a          
2        |2       |b     

ApartmanMalk

BlockCode|arsehRow|SakhtemanRow|name
-------------------------------------------------
3        |3       |01          |d       

如果Renovationinfo

,我希望与ArsehMalk加入SakhtemanRow=='00'

如果Renovationinfo

,则ApartmanMalk加入SakhtemanRow<>'00'

我写这个查询但是这不会返回任何东西。

Select name
From 
    Renovationinfo r 
Left Join
     ArsehMalk m1 On m1.BlockCode = r.BlockCode And
     m1.arsehRow = r.arsehRow And r.SakhtemanRow = '00' 
Left Join
     ApartmanMalk m2 On m2.BlockCode = r.BlockCode And
     m2.arsehRow = r.arsehRow And
     m2.SakhtemanRow=r.SakhtemanRow  And 
     r.SakhtemanRow<>'00' 

我想获得此输出

BlockCode|arsehRow|name
-------------------------------
1        |1       |a          
2        |2       |b          
3        |3       |d   

1 个答案:

答案 0 :(得分:3)

您的查询有一个基本问题:name含糊不清。您可以将其修复为:

select coalesce(m1.name, m2.name) as name

因为您需要其他列:

select r.BlockCode, r.arehRow, coalesce(m1.name, m2.name) as name