1

您能否让我知道如何根据条件离开加入两个不同的表?我很感激任何帮助。

SELECT A.id,
       A.flag,
       B.fname,
       B.lname
FROM   Table1 A
       CASE 
            WHEN ISNULL(A.flag, 0) = 0 THEN LEFT
       JOIN Table2 B
            ON  B.id = A.id
                ELSE
       LEFT JOIN Table3 B
            ON  B.id = A.id
4

4 回答 4

2

你不能。但是您可以连接两个表,然后在select子句中选择您想要的值:

SELECT A.id, A.flag,
       (case when coalesce(A.flag, 0) = 0 then b.fname else c.fname end) as fname,
       (case when coalesce(A.flag, 0) = 0 then B.lname else c.lname end) as lname
FROM Table1 A left outer join
     Table2 B
     on B.id = A.id left outer join
     Table3 C
     on c.id = A.id

如果 Table2 或 Table3 中有任何 id 的多行,这将产生额外的行。

作为一种通常效率较低的替代方法,您还可以执行以下操作:

select a.id, a.flag,
       MAX(case when coalesce(A.flag, 0) = 0 and which = 'b' or
                     coalesce(A.flag, 0) <> 0 and which = 'c'
                then b.fname
           end) as fname,
       MAX(case when coalesce(A.flag, 0) = 0 and which = 'b' or
                     coalesce(A.flag, 0) <> 0 and which = 'c'
                then b.lname
           end) as lname
from table1 A left outer join
     ((select b.*, 'b' as which from table2 b)
      union all
      (select c.*, 'c' as which from table3 c)
     ) b
group by a.id, a.flag

group by将消除不需要的重复项。

于 2013-02-08T19:39:34.747 回答
0

Since the table to join is dependent on the A.flag, you should apply that knowledge in the join clause...

SELECT A.id, A.flag, 
    fname = coalesce(t2.fname, t3.fname), 
    lname = coalesce(t2.lname, t3.lname)
FROM Table1 A
LEFT JOIN Table2 t2 on t2.id = A.id and isnull(A.flag, 0) = 0
LEFT JOIN Table3 t3 on t3.id = A.id and isnull(A.flag, 0) = 1
于 2013-02-08T19:50:21.443 回答
0
SELECT A.id,
       A.flag,
       CASE 
            WHEN ISNULL(A.flag, 0) = 0 THEN B1.fname
            ELSE B2.fname
       END as fname,
       CASE 
            WHEN ISNULL(A.flag, 0) = 0 THEN B1.lname
            ELSE B2.lname
       END as lname
FROM   Table1 A
       LEFT JOIN Table2 B1
            ON  B1.id = A.id
       LEFT JOIN Table3 B2
            ON  B2.id = A.id

尝试这个:

 CASE 
        WHEN ISNULL(A.flag, 0) = 0 THEN B1.fname + ' ' + B1.lname
            ELSE B2.fname + ' ' + B2.lname
        END as name
于 2013-02-08T19:43:51.590 回答
0

你不能直接做。然而,有一种完全不直观的方式实际上是有效的。您使用不同的条件进行左连接并合并。像这样的东西。

select a.id
, coalesce(c.name, b.name, 'no name found') name

from tableA a left join tableB b on a.field1 = b.field1
left join tableC c on a.field1 = c.field2

etc
于 2013-02-08T19:45:03.497 回答