单独的 LINQ2SQL selects 与 group 和 join 在两个索引表上的性能与一个组合 select 的性能

Performance of separate LINQ2SQL selects with group and join on two indexed tables vs. one combined select

我需要从table (tab_activities) 中检索记录,按ID 分组,仅按日期确定每组的最新记录。 在这些最新记录中,我只需要那些尚未设置特定 属性(已完成)的记录。 最后,我必须核对是否有任何活动也在黑名单中注册 (tab_flaggedActivities),然后对所有未完成且未标记的活动做一些事情。

两个 table 都有 id 的索引。 显然,id 不是主键。

我不确定我正在做的是否是设置此 select 的最有效方法。 将这些单独的 select 合并为一个 select 是否更好?如果是,我该怎么做?

// Retrieve only the latest activity entry of each known activity-ID
var latestActivityRecords = from activity in dc.tab_activities
                            where activity.dateRegistered > DateTime.Now.AddDays(-MaxAge)
                            group activity by activity.id
                            into groups
                            select groups.OrderByDescending(p => p.dateRegistered).First();

// Filter activities that are not finished
var unfinishedActivityRecords = from activity in latestActivityRecords
                                where !activity.finished
                                select activity;

// Check if any of those are in blacklist (different table)
var flaggedActivityRecords = from activity in unfinishedActivityRecords
                             join flaggedActivity in dc.tab_flaggedActivities 
                             on activity.id equals flaggedActivity.id
                             select activity;

if (unfinishedActivities != null)
{
    // Do something with all unfinished / unflagged activities 
    foreach (var activityRecord in unfinishedActivityRecords)
    {
        if (!flaggedActivityRecords.Any(p => p.id == activityRecord.id))
        {
            DoSomething(activityRecord);
        }
    }
}

如果您的意思是将 if Any 测试与查询相结合,您可以颠倒上次查询的含义并只循环结果,在数据库服务器上执行过滤:

var unflaggedActivityRecords = from activity in unfinishedActivityRecords
                               where !dc.tab_flaggedActivities.Select(fa => fa.id).Contains(activity.id)
                               select activity;

if (unfinishedActivities != null) {
    // Do something with all unfinished / unflagged activities 
    foreach (var activityRecord in unflaggedActivityRecords) {
        DoSomething(activityRecord);
    }
}