一個聯盟而不存在測試似乎是這樣的方式去
select *
from company C
inner join CompanyAddress A on A.companyID = C.companyID
where A.AddressType = 1
union all
select *
from company C
LEFT join CompanyAddress A on A.companyID = C.companyID
and A.AddressType = 2
and not exists (
select *
from CompanyAddress B
where B.companyID = C.companyID
and B.AddressType = 1)
第二部分使用左連接,以便既沒有地址類型1也沒有2的公司仍將顯示。
要麼是這樣,要麼使用左連接來AddressType = 2,只有當第一個連接(type = 1)失敗時纔會觸發。
select C.*,
coalesce(A.addressType, B.addressType) addressType,
coalesce(A.streetname, B.streetname) streetname
from company C
left join CompanyAddress A on A.companyID = C.companyID and A.AddressType = 1
left join CompanyAddress B on A.companyID is null
AND B.companyID = C.companyID and B.AddressType = 2
正如你所看到的,這是很難,因爲從地址每一列都必須經過3210 A和B之間
+1這將與DB2 for IBM i V5R4 – 2011-02-03 16:19:33