0

我有三个需要加入的表。

Table1 有列 id、Name、idObject、lineItem。Table2 有列 id、City、idLineItem、idOrder、idSupplier、idAdv。表 3 具有列 idAdv、State。

我的查询是:

select Table1.id, Table1.Name, Table1.idObject, Table2.City, Table3.State
from Table1 
join Table2 ON case 
                 when Table1.Name='abc' then Table1.idObject=Table2.idLineItem
                 when Table1.Name='def' then Table1.idObject=Table2.idOrder
                 else Table1.idObject=Table2.idSupplier
               end
join Table3 on Table2.idAdv=Table3.idAdv
group by Table1.id, Table1.idObject;
4

2 回答 2

1

CASE 语句只能返回一个值,因此您必须将比较移到 CASE 之外。像这样的东西:

select Table1.id, Table1.Name, Table1.idObject, Table2.City, Table3.State
from Table1 
join Table2 ON Table1.idObject = case 
                 when Table1.Name='abc' then Table2.idLineItem
                 when Table1.Name='def' then Table2.idOrder
                 else Table2.idSupplier
               end
join Table3 on Table2.idAdv=Table3.idAdv
group by Table1.id, Table1.idObject;
于 2013-03-05T00:46:44.453 回答
1

可能..

select Table1.id, Table1.Name, Table1.idObject, Table2.City, Table3.State 
from Table1 
join Table2 ON
   (Table1.Name='abc' and Table1.idObject=Table2.idLineItem) 
OR (Table1.Name='def' and Table1.idObject=Table2.idOrder) 
OR (Table1.Name <> 'abc' and Table1.Name <> 'def' and Table1.idObject=Table2.idSupplier) 
join Table3 on Table2.idAdv=Table3.idAdv 
group by Table1.id, Table1.idObject;

不过最好检查一下执行计划。

于 2013-03-05T01:21:25.520 回答