【发布时间】:2012-12-11 23:15:07
【问题描述】:
我正在运行这个查询:
List<RerocdByGeo> reports = (from p in db.SOMETABLE.ToList()
where (p.colID == prog && p.status != "some_string" && p.col_date < enddate && p.col_date > startdate)
group p by new {
country = (
(p.some_integer_that_represents_an_id <= -0) ? "unknown" : (from f in db.A_LAGE_TABLE where (f.ID == p.some_integer_that_represents_and_id) select f.COUNTRIES_TABLE.COU_Name).FirstOrDefault()),
p.status }
into g
select new TransRerocdByGeo
{
ColA = g.Sum(x => x.ColA),
ColB = g.Sum(x => x.ColB),
Percentage = (g.Sum(x => x.ColA) != null && g.Sum(x => x.ColA) != 0) ? (g.Sum(x => x.ColB) / g.Sum(x => x.ColA)) * 100 : 0,
Status = g.Key.status,
Country = g.Key.country
}).ToList();
在 sql 中针对同一个数据库的类似查询将运行几秒钟,而在好的情况下,这个查询大约需要 30-60 秒...
表 SOMETABLE 包含大约 10-60 K 行 此处称为 A_LARGE_TABLE 的表包含大约 10-20 行
coulmn some_inteher_that_reoresents_an_id 是大表上的 id 但也可以是 0 或 -1 并且需要获取“未知”值,所以我无法建立关系(或者我可以吗?如果可以请解释)
COUNTRIES_TABLE 包含 100-200 行。
coulID 和 ID 是标识列 ...
有什么建议吗?
【问题讨论】:
-
您可以先删除
ToList()。 -
您是否将 LINQ 查询生成的 SQL 与您为获取相同数据而编写的 SQL 查询进行了比较。这将是我的出发点,我敢打赌它生成的 SQL 不是最优的。
-
@BenRobinson SQL 是
select * from SOMETABLE,因为他ToLists 开头的表。 -
@Servy,哈哈,是的,刚刚注意到了。
标签: c# sql linq entity-framework