我有以下4个表: MainTable,仓库,客户和公司。
这些表的模式:
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)该对象的作用是获取(MainTable的)对应ID的Country_ID和Zone_ID。
我们有两种不同的情况:if MainTable.Warehouse_ID不为空我们应该对仓库表(字段warehouse_id)进行内连接,然后对公司表(对字段Company_ID),else (如果MainTable.Warehouse_ID为空)进行内连接,我们应该对客户表(对Customer_ID字段)进行内连接,然后对公司表(对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)我是否正确地使用了一个我遗漏的小语法错误?如果not..is有其他方法可以做到吗?
谢谢
发布于 2014-10-09 19:11:54
您可以使用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发布于 2014-10-09 19:13:13
尝试如下所示:
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 发布于 2014-10-09 19:06:14
你不能这么做。使用这种条件连接,你期望输出是的是什么?
你有没有试过使用外连接?
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_IDhttps://stackoverflow.com/questions/26276700
复制相似问题