【问题标题】:One to many join to last modified record in the most efficient way以最有效的方式一对多连接到最后修改的记录
【发布时间】:2014-07-22 14:36:15
【问题描述】:

我知道以前有人问过这个问题的变体,但我想知道对我的特定问题最有效的解决方案。

我有两张桌子...

事件(event_id、customer_email...)

客户(customer_email、last_modified...)

我要加入这两个表,并且只希望拥有最大 last_modified 日期的客户。客户表绝对是巨大的,所以想知道解决这个问题的最佳方法。

【问题讨论】:

  • 那么这更多是关于如何为您的数据建立索引而不仅仅是查询......我可以向您展示一个查询,但如果没有正确索引,性能可能会很差
  • @t-mckeown - 您好,感谢您的回复。你能告诉我查询吗,我可以测试它。谢谢!

标签: sql-server performance join one-to-many


【解决方案1】:

抛开索引,这是您可以使用的查询:

SELECT <columns you want>
FROM Event AS E
JOIN Customer AS C
  ON C.Customer_Email = E.Customer_Email
JOIN ( SELECT C1.Customer_Email, MAX(C1.Last_Modified) AS LastModified
       FROM Customer AS C1
       GROUP BY C1.Customer_Email
) AS C2
ON C2.Customer_Email = C.Customer_Email
AND C2.LastModified = C.Last_Modified

【讨论】:

    【解决方案2】:

    使用row_number

    select * 
    from 
    (
    select *, Row_number() over (partition by Event_ID order by Last_Modified desc) rn
    from Event 
        inner join Customer 
        on Event.Customer_Email = Customer.Customer_Email
    ) v
    where rn = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多