我需要加入三张桌子。
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;
答案 0 :(得分: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;
答案 1 :(得分: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;
更好地检查执行计划。