内连接时的情况

时间:2014-10-09 10:58:48

标签: sql-server case inner-join

我有以下4个表:MainTable,Warehouse,Customer和Company。

这些表的架构:

create table MainTable(ID int, Warehouse_id int, Customer_ID int)
create table Warehouse (Warehouse_id int, company_id int)
create table Customer (Customer_ID int, Company_ID int)
create table company (Company_id int, Country_ID int, Zone_ID int)

目标是获取相应ID(MainTable)的Country_ID和Zone_ID。

我们有两种不同的情况:if MainTable.Warehouse_ID不为空我们应该在Warehouse表上进行内连接(在字段warehouse_id上​​),然后在Company表上进行连接(在字段Company_ID上), else(如果MainTable.Warehouse_ID为null)我们应该在Customer Table(在Customer_ID字段上)然后在Company Table(在Company_ID字段上)上进行内部联接。

以下查询在单词' case':

附近生成错误
select CO.Country_ID, CO.Zone_ID
from    MainTable MT 
inner join (case 
    when MT.Warehouse_ID is not null 
then
         Warehouse W on MT.Warehouse_ID=W.Warehouse_ID 
        inner join Company CO on W.Company_ID=CO.Company_ID
else     
         Customer Cu on MT.Customer_ID=Cu.Customer_ID
        inner join Company C on Cu.Company_ID=CO.Company_ID
    end)

我是否正确地使用我错过的小语法错误?如果不是..有没有其他方法可以做到这一点?

由于

3 个答案:

答案 0 :(得分:1)

您可以使用UNION

SELECT CO.Country_ID, CO.Zone_ID
  FROM MainTable MT
  INNER JOIN Warehouse W ON MT.Warehouse_ID=W.Warehouse_ID
  INNER JOIN Company CO on W.Company_ID=CO.Company_ID
  WHERE MT.Warehouse_ID IS NOT NULL
UNION
SELECT CO.Country_ID, CO.Zone_ID
  FROM MainTable MT
  INNER JOIN Customer Cu ON MT.Customer_ID=Cu.Customer_ID
  INNER JOIN Company CO on Cu.Company_ID=CO.Company_ID
  WHERE MT.Warehouse_ID IS NULL

答案 1 :(得分:1)

尝试以下内容:

IF EXISTS(SELECT 1
          FROM   MainTable mt
          WHERE  mt.Warehouse_ID IS NOT NULL)
  BEGIN
      SELECT CO.Country_ID,
             CO.Zone_ID
      FROM   MainTable MT
             INNER JOIN Warehouse W
                     ON MT.Warehouse_ID = W.Warehouse_ID
             INNER JOIN Company CO
                     ON W.Company_ID = CO.Company_ID
  END
ELSE
  BEGIN
      SELECT CO.Country_ID,
             CO.Zone_ID
      FROM   MainTable MT
             INNER JOIN Customer Cu
                     ON MT.Customer_ID = Cu.Customer_ID
             INNER JOIN Company C
                     ON Cu.Company_ID = CO.Company_ID
  END 

答案 2 :(得分:-1)

你不能这样做。 对于这种条件连接,您希望输出是什么?

您是否尝试过使用外连接?

select ISNULL(C1.Country_ID,C2.Country_ID) as Country_ID,ISNULL(C1.Zone_ID,C2.Zone_ID) as Zone_ID
from    MainTable MT 
left outer join  Warehouse W on MT.Warehouse_ID=W.Warehouse_ID 
left outer join Company1 C1 on W.Company_ID=C1.Company_ID
left outer join Customer Cu on MT.Customer_ID=Cu.Customer_ID
left outer join Company2 C2 on Cu.Company_ID=C2.Company_ID