SQL:如何从这 3 个表中 select 数据

SQL: How to select data from this 3 tables

我有 3 个表:项目、公司、地址,如下所示:

项目

公司

地址

规则是,如果一个项目有一个AddressID,那么直接从Address中获取街道。 如果没有,则通过公司获取地址和街道。

我可以在一个 SQL 查询中解决这个问题吗?

试试这样的东西:

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(公司地址)

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
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 returns Project.AddressID 如果不为空;如果它是 null 那么它 returns c.AddressID