条件3表加入

时间:2014-05-06 03:46:14

标签: mysql sql

表1

PropertyId

1
2
3
4
5
6

表2

PropertyID PropertyCode PropList ID

1            2            45
3            4            67
5            6            89

表3

PropertyID IType

1           3     
2           3     
3          11    
4          11    
5           3
6           3

目标表

PropertyID   PropertyCode

1             45
2             45
3             67
4             67
5             89
6             89

步骤1:加入表1和表3

步骤2:如果Table 1.PropertyId.Itype = 3然后加入Table1.PropertyID = Table2.PropertyId

上的表1和表3

否则

步骤3:如果Table 1.PropertyId.Itype = 11然后加入Table1.PropertyID = Table2.PropListId

上的表1和表3

很抱歉重新发布,但想要正确发布问题。

我真的很感激一些帮助。谢谢。

2 个答案:

答案 0 :(得分:0)

也许,这样的事情:

;
WITH    joinedt1
          AS ( SELECT   a.PropertyId AS PropertyId ,
                        b.IType AS IType
               FROM     tab1 a
                        LEFT JOIN tab3 b ON a.PropertyId = b.PropertyID
             )
    SELECT  A1.PropertyId ,
            C.PropList_ID
    FROM    joinedt1 A1
            INNER JOIN TABLE2 C ON A1.PropertyId = C.PropertyId
    WHERE   A1.IType = 3
    UNION
    SELECT  A2.PropertyId ,
            D.PropList_ID
    FROM    joinedt1 A2
            INNER JOIN TABLE2 D ON A2.PropertyId = D.PropListId
    WHERE   A2.IType = 11

答案 1 :(得分:0)

您的说明和专栏定义不匹配,请您更正?

多重IF ...那么通常转换为CASE,这可能是你想要的:

FROM T1 
JOIN T3 
  ON T1.PropertyID = T3.PropertyID
JOIN T2
  ON T1.PropertyID = 
     CASE T3.Itype 
        WHEN  3 THEN T2.PropertyId
        WHEN 11 THEN T2.PropListId
     END