我在数据库中有四个表:
CustomerMaster
,Addresses
,EmailAddresses
,& PhoneNumbers
Addresses
,EmailAddresses
,& PhoneNumbers
引用CustomerMaster
的主键。
我想创建一个查询,以便在CustomerMaster
中获取每位客户的最新客户信息。我知道如何将表格加在一起,但我不知道如何利用TimeStamp
字段仅从Addresses
,EmailAddresses
和{中检索最近更新的数据{1}}中每位客户的{1}}表。
SQL小提琴: Working Example
CustomerMaster:
PhoneNumbers
地址:
CustomerMaster
EmailAddresses:
| CUS_PK | CUS_FirstName | CUS_LastName | CUS_AccountNum
| 1 | mickey | mouse | 000001
| 2 | donald | duck | 100000
PHONENUMBERS:
| ADD_CUS_FK | ADD_StreetAddress | ADD_City | ADD_StateProvince | ADD_PostalCode | ADD_TimeStamp
| 1 | Disney World | Orlando | Florida | 99999 | 2000-01-01 12:00:00.000
| 1 | Disney Land | Anaheim | California | 12345 | 2012-12-23 12:00:00.000
| 2 | Disney World | Orlando | Florida | 99999 | 2001-01-01 12:00:00.000
查询:
| EMA_CUS_FK | EMA_EmailAddress | EMA_TimeStamp
| 1 | supermouse@disney.com | 2005-01-01 12:00:00.000
| 1 | mousehouse@disney.com | 2006-01-01 12:00:00.000
| 2 | scrougeheir@disney.com | 2001-01-01 12:00:00.000
当前结果:
| PHO_CUS_FK | PHO_PhoneNumber | PHO_TimeStamp
| 1 | 999-999-9999 | 2001-01-01 12:00:00.000
| 1 | 012-345-6789 | 2013-01-01 12:00:00.000
| 2 | 666-867-5309 | 2001-01-01 12:00:00.000
期望的结果:
SELECT DISTINCT cm.CUS_FirstName, cm.CUS_LastName, cm.CUS_AccountNum,
addr.ADD_StreetAddress, addr.ADD_City,
addr.ADD_StateProvince, addr.ADD_PostalCode,
email.EMA_EmailAddress, phone.PHO_PhoneNumber
FROM CustomerMaster AS cm
JOIN Addresses AS addr
ON cm.CUS_PK = addr.ADD_CUS_FK
JOIN EmailAddresses AS email
ON cm.CUS_PK = email.EMA_CUS_FK
JOIN PhoneNumbers AS phone
ON cm.CUS_PK = phone.PHO_CUS_FK
ORDER BY cm.CUS_AccountNum
我如何编辑现有查询以获得所需的结果集?
请提供增强的SQL查询(最好是SQL小提琴)
答案 0 :(得分:0)
显然, LEFT JOIN
和 NULL
检查是解决方案:
<强>查询:强>
SELECT DISTINCT cm.CUS_FirstName, cm.CUS_LastName, cm.CUS_AccountNum,
addrs1.ADD_StreetAddress, addrs1.ADD_City, addrs1.ADD_StateProvince,
addrs1.ADD_PostalCode, email1.EMA_EmailAddress, phone1.PHO_PhoneNumber
FROM CustomerMaster AS cm
JOIN Addresses AS addrs1
ON cm.CUS_PK = addrs1.ADD_CUS_FK
LEFT JOIN Addresses AS addrs2
ON cm.CUS_PK = addrs2.ADD_CUS_FK
AND addrs1.ADD_TimeStamp < addrs2.ADD_TimeStamp
JOIN EmailAddresses AS email1
ON cm.CUS_PK = email1.EMA_CUS_FK
LEFT JOIN EmailAddresses AS email2
ON cm.CUS_PK = email2.EMA_CUS_FK
AND email1.EMA_TimeStamp < email2.EMA_TimeStamp
JOIN PhoneNumbers AS phone1
ON cm.CUS_PK = phone1.PHO_CUS_FK
LEFT JOIN PhoneNumbers AS phone2
ON cm.CUS_PK = phone2.PHO_CUS_FK
AND phone1.PHO_TimeStamp < phone2.PHO_TimeStamp
WHERE phone2.PHO_TimeStamp IS NULL
AND addrs2.ADD_TimeStamp IS NULL
AND email2.EMA_TimeStamp IS NULL
ORDER BY cm.CUS_AccountNum
SQL小提琴: here
答案 1 :(得分:-1)
你不能只使用子查询作为select子句中的字段。每个表的一个子查询,您希望获得最新的值。子查询可以是例如下降时间戳上的“TOP 1”。