如何根据条件加入两个表?

时间:2015-02-25 10:09:50

标签: sql-server sql-server-2008

有三个表A,B,C

表格列是姓名,ID,地址

B表格列是ID,地址,学校

C表列是学校,地址,咖啡馆

如果Name ='A' 然后表A和表B将基于A.ID = B.ID

加入

如果名称='B'

然后表A和表B将基于A.ID = B.ID和A.Address = B.Address

加入

这个结果加入表C

4 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

SELECT * 
FROM A
INNER JOIN B 
  ON (   (B.Name = 'A' AND A.ID = B.ID) 
      OR (B.Name = 'B' AND A.ID = B.ID AND A.Address=B.Address)
     )

您现在可以使用表C

加入结果

谢谢

答案 1 :(得分:0)

使用ORAND运算符模拟if子句中的ON条件。试试这个Join

SELECT *
FROM   A
       INNER JOIN B
               ON ( A.name = 'A'
                    AND A.ID = B.ID )
                   OR ( A.Name = 'B'
                        AND A.ID = B.ID
                        AND A.Address = B.Address )
       INNER JOIN C
               ON B.school = C.school 

答案 2 :(得分:0)

假设A.Name是A或B:

SELECT *
FROM   A
  JOIN B ON ( A.ID = B.ID )
            AND ( A.Name = 'A' OR A.Address = B.Address )
  JOIN C ON B.school = C.school 

答案 3 :(得分:0)

SELECT * FROM A INNER JOIN B
    ON A.ID = B.ID
    INNER JOIN C
    ON B.SCHOOL = C.SCHOOL
WHERE A.NAME = 'A'
UNION ALL
SELECT * FROM A INNER JOIN B
    ON A.ID =B.ID and A.Address=B.Address
    INNER JOIN C
    ON B.SCHOOL = C.SCHOOL
    WHERE A.NAME = 'B'

这可能有效