我有3个表:项目,公司,地址,如下所示:
规则是,如果项目具有AddressID,则直接从地址获取Street。 如果没有,那么通过公司获取地址和街道。
我可以在一个SQL查询中解决这个问题吗?
答案 0 :(得分:1)
尝试这样的事情:
select p.ProjectID, coalesce(a1.Street, a2.Street)
from Project p inner join
Company c on p.CompanyID = c.CompanyID left join
Address a1 on p.AddressID = a1.AddressID left join
Address a2 on c.AddressID = a2.AddressID
如果a1.Street为null(项目中列出的地址),则返回a2.Street(公司地址)
答案 1 :(得分:1)
select p.*, case when p.addressid is not null
then ap.street
else ac.street
end as street
from project p
left join company c on c.companyid = p.companyid
left join address ap on ap.addressid = p.addressid
left join address ac on ac.addressid = c.addressid
答案 2 :(得分:1)
SELECT p.ProjectID, p.CompanyID, a.AddressID, a.Street
FROM Project p
INNER JOIN Company c
ON p.CompanyID = c.CompanyID
INNER JOIN Address a
ON ISNULL(p.AddressID, c.AddressID) = a.AddressID
ISNULL
如果不为空,则返回Project.AddressID
;如果为null则返回c.AddressID