Sql server 2008 r2 如何从两个表中获得单个结果,其中第二个表包含第一个表中记录的更新版本?
我有两个表,Sql server 2008 r2 如何从两个表中获得单个结果,其中第二个表包含第一个表中记录的更新版本?,sql-server-2008-r2,left-join,Sql Server 2008 R2,Left Join,我有两个表,companyaddress&mycompanyaddress。(改名以保护罪犯) companyaddress保存公司的默认地址列表。这些记录是不可变的。用户可以更改公司地址的详细信息,但这些更改将存储在MyCompanyAddresss中 如何从两个表中生成一个地址列表,排除companyaddress中存在相应记录的mycompanyaddress中的记录 样本数据 公司地址 DatabaseId | Id | Code | Name | Street
companyaddress
&mycompanyaddress
。(改名以保护罪犯)
companyaddress
保存公司的默认地址列表。这些记录是不可变的。用户可以更改公司地址的详细信息,但这些更改将存储在MyCompanyAddresss中
如何从两个表中生成一个地址列表,排除companyaddress
中存在相应记录的mycompanyaddress
中的记录
样本数据
公司地址
DatabaseId | Id | Code | Name | Street | City | Zip | Maint Date
1 | Guid1 | APL | Apple | 1 Infinite Loop | Cupertino | 95014 | 11/1/2012
2 | Guid2 | MS | Microsoft | One Microsoft Way | Redmond | 98052 | 11/1/2012
DatabaseId | Id | Code | Name | Street | City | Zip | Maint Date
5 | Guid3 | APL | Apple | Updated Address | Cupertino | 95014 | 11/6/2012
MyCompanyAddress
DatabaseId | Id | Code | Name | Street | City | Zip | Maint Date
1 | Guid1 | APL | Apple | 1 Infinite Loop | Cupertino | 95014 | 11/1/2012
2 | Guid2 | MS | Microsoft | One Microsoft Way | Redmond | 98052 | 11/1/2012
DatabaseId | Id | Code | Name | Street | City | Zip | Maint Date
5 | Guid3 | APL | Apple | Updated Address | Cupertino | 95014 | 11/6/2012
预期结果
DatabaseId | Id | Code | Name | Street | City | Zip | Maint Date
2 | Guid2 | MS | Microsoft | One Microsoft Way | Redmond | 98052 | 11/1/2012
5 | Guid3 | APL | Apple | Updated Address | Cupertino | 95014 | 11/6/2012
我尝试了MS SQL的UNION
,的各种排列,除了和INTERSECT
之外,都没有用。另外,我也不相信加入是答案,但我很高兴我被证明是错的
数据库设计可以更改,但最好保持不变。将左连接与合并结合使用。如果联接找到匹配项,则合并将从覆盖的行中选择值。如果未找到匹配项,则返回原始值
SELECT ca.DatabaseId,
COALESCE(mca.Id, ca.Id) AS Id,
COALESCE(mca.Name, ca.Name) AS Name,
COALESCE(mca.Street, ca.Street) AS Street,
COALESCE(mca.City, ca.City) AS City,
COALESCE(mca.Zip, ca.Zip) AS Zip,
COALESCE(mca.MaintDate, ca.MaintDate) AS MaintDate,
FROM CompanyAddresses ca
LEFT JOIN MyCompanyAddresses mca
ON ca.Code = mca.Code;
DatabaseId在不同的表中是不同的。我更新了问题以反映这一点。但是,我有一个相同的code
字段。我看看你的建议如何。