MSSQL:左连接三个表中的多个列

Posted

技术标签:

【中文标题】MSSQL:左连接三个表中的多个列【英文标题】:MSSQL: left join multiple columns in three tables 【发布时间】:2021-12-31 16:52:58 【问题描述】:

我在 MS SQL Server 中有三个表:

Tenants:
TenantID int,
LastName varchar(50),
FirstName varchar(50)

Intervals:
Value int,
Name varchar(50)

Leases:
LeaseID int,
Interval int,
StartDate date,
EndDate date,
Tenant1 int,
Tenant2 int,
Tenant3 int,
Tenant4 int

Intervals 表有三行:[1,'Monthly']、[2,'BiWeekly'] 和 [3,'Weekly']

我需要一个具有此结果集的查询:

LID Type      Start         End      Tenant1       Tenant2        Tenant3       Tenant4
21  Monthly  12/15/2019  12/15/2020  Sean Murphy   Audrey Moore   Randy Davis
32  Weekly   06/01/2018              Pete Higgins  Kathy Higgins  
35  Monthly  08/01/2019  10/31/2020  Andy Stacke   Valerie Stacke
44  Monthly  01/01/2021              Pete O'Toole  Martha White   

暂时先不管名字+姓氏列,我第一次尝试成功地使用了两个左连接:

select L.LeaseID, I.Name as Type, L.StartDate, L.EndDate, T.LastName as Tenant1 
from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Tenant1

并返回:

LID Type      Start         End      Tenant1 
21  Monthly  12/15/2019  12/15/2020  Murphy  
32  Weekly   06/01/2018              Higgins
35  Monthly  08/01/2019  10/31/2020  Stacke
44  Monthly  01/01/2021              O'Toole

一个好的开始,但我似乎无法从租户表中获得最多 4 个唯一名称,我想在租户列中组合 (firstname+lastname)。

我为同一个表(租户)尝试了多个左连接,并在一个连接上尝试了 ORing 条件;他们在直觉上似乎都是错误的。

select L.lid,L.ruid, I.Name, T.LastName as Tenant1, T.LastName as Tenant2 from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Ten1
left join Tenants T on T.TID = L.Ten2

select L.lid,L.ruid, I.Name, T.LastName as Tenant1, T.Lastname as Tenant2 from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T on T.TID = L.Ten1 or T.TID = L.Ten2  

但它们都在两列中返回相同的姓氏。

【问题讨论】:

【参考方案1】:

在这里没有网络但我相信你想要这样的东西:

select 
    L.LeaseID AS 'LID', 
    I.Name AS 'Type', 
    L.StartDate AS 'Start', 
    L.EndDate AS 'End', 
    CONCAT(T1.FirstName, ' ', T1.LastName) AS 'Tenant1', 
    CONCAT(T2.FirstName, ' ', T2.LastName) AS 'Tenant2', 
    CONCAT(T3.FirstName, ' ', T3.LastName) AS 'Tenant3', 
    CONCAT(T4.FirstName, ' ', T4.LastName) AS 'Tenant4'
from Leases L
left join Intervals I ON L.Interval = I.Value
left join Tenants T1 ON L.Tenant1 = T1.TenantID
left join Tenants T2 ON L.Tenant2 = T2.TenantID
left join Tenants T3 ON L.Tenant3 = T3.TenantID
left join Tenants T4 ON L.Tenant4 = T4.TenantID

【讨论】:

【参考方案2】:

试试这个

select
  L.lid
  ,L.ruid
  , I.Name
  , T1.LastName as Tenant1
  , T2.LastName as Tenant2 
from Leases L 
left join Intervaltypes I on I.value=L.Interval 
left join Tenants T1 on T1.TID = L.Ten1
left join Tenants T2 on T2.TID = L.Ten2

【讨论】:

阿赫。很简单,很好用,谢谢

以上是关于MSSQL:左连接三个表中的多个列的主要内容,如果未能解决你的问题,请参考以下文章

sql mssql,外部应用,多选左连接和外部aaply所以它不会返回多个(lef join)结果

外连接查询

BigQuery 中的多个左连接

在mysql中使用左连接在三个表之间更新

如何使 React Table 中的某些列左对齐和某些列居中对齐 - React

数据库操作中,左连接,右连接是啥意思,举例说明