一对多以最有效的方式加入到最后修改的记录

时间:2014-07-22 14:36:15

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

我意识到之前已经提出过这个问题的变体,但我想知道对我的特定问题最有效的解决方案。

我有两张桌子......

活动(event_id,customer_email ...)

客户(customer_email,last_modified ......)

我加入了这两个表,只希望客户的last_modified日期最长。客户表非常庞大,所以想知道最好的方法。

2 个答案:

答案 0 :(得分:0)

设置索引,这是您可以使用的查询:

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

答案 1 :(得分:0)

使用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