LinqToSql - 多个子查询创建许多往返

时间:2009-04-10 22:18:13

标签: .net linq linq-to-sql

我有两张看起来像这样的表:

alt text http://www.brettrobichaud.com/images/linq.png

我正在尝试从ApplianceStatisticsLog生成包含每个时段的两个特定StatisticsNames的查询。以下是我提出的Linq查询。它可以工作,但为第一个子选择生成单个查询,然后为第二个子选择生成一个额外的EACH记录查询。哎呀,数据库往返正在杀死我。

如何重新设计以挤出单个SQL查询?

from l in ApplianceStatisticsLogs
where l.ApplianceServerId > 1
orderby l.PeriodEndUtc ascending
select new
{
Time = l.PeriodEndUtc,
Stat1 = from s in ApplianceStatistics
        where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
          &&  s.ApplianceStatisticNameId == 2
        select s.Value,
Stat2 = from s in ApplianceStatistics
        where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
          &&  s.ApplianceStatisticNameId == 3
        select s.Value
}

2 个答案:

答案 0 :(得分:1)

更新(基于关系)

select new
{
Time = l.PeriodEndUtc,
Stat1 = (from s in l.ApplianceStatistics
         where s.ApplianceStatisticNameId == 2
         select s.Value
       ).ToList(),
Stat2 = (from s in l.ApplianceStatistics
         where s.ApplianceStatisticNameId == 3
         select s.Value
       ).ToList()
}

<强>尝试

select new
{
Time = l.PeriodEndUtc,
Stat1 = (from s in ApplianceStatistics
                where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
                  &&  s.ApplianceStatisticNameId == 2
                select s.Value
       ).ToList(),
Stat2 = (from s in ApplianceStatistics
                where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
                  &&  s.ApplianceStatisticNameId == 3
                select s.Value
       ).ToList()
}

答案 1 :(得分:0)

弗雷迪走在正确的轨道上,几乎拥有它。解决方案最终是为每个子查询使用First()。如:

from l in ApplianceStatisticsLogs
where l.ApplianceServerId > 1
orderby l.PeriodEndUtc ascending
select new
{
    Time = l.PeriodEndUtc,
    Stat1 = (from s in ApplianceStatistic
            where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
              &&  s.ApplianceStatisticNameId == 2
            select s.Value).First(),
    Stat2 = (from s in ApplianceStatistics
            where s.ApplianceStatisticsLogId == l.ApplianceStatisticsLogId
              &&  s.ApplianceStatisticNameId == 3
            select s.Value).First()
}

我忽略了提到在子查询中只有一条记录匹配。感谢Freddy的帮助!