【问题标题】:SQL select Count with where very slowSQL select Count with where 非常慢
【发布时间】:2013-04-10 11:48:51
【问题描述】:

我在我的程序中多次使用count() 函数:

var housewith2floor = from qry in houses
where qry.floor == 2
select qry;

var counthousewith2floor = housewith2floor.count();

var housecolorwhite = from qry in house
where qry.color == "white"
select qry;

var countwhotehouse = housecolorwhite.count();

每个count 方法都需要很长时间才能执行。该数据库有 200 万行数据。我已经为 floor 列和 color 列放置了一个非聚集索引,但是计数仍然需要太长时间。有没有其他方法可以让我的计数运行得更快?

【问题讨论】:

  • 使用 LINQ 的次数不多(只使用了一点 EF),但我敢打赌,您可以通过在 DB 端而不是在您的代码后面进行计算来加快计数。
  • dbcontext 的隔离级别是多少?
  • 检查数据库实际运行的内容。运行跟踪或在var housecolorwhite 处设置断点并将鼠标悬停在counthousewith2floor 上。
  • 我使用 ReadUncommitted 作为隔离级别,但仍然很慢...
  • 这是否比直接 SQL 查询慢很多?

标签: sql performance linq count


【解决方案1】:

这不是需要时间的计数。初始语句在需要之前不会真正执行(称为deferred execution)。所以这是由

生成的查询
var housewith2floor = from qry in houses
where qry.floor == 2
select qry;

这需要时间。

编辑删除关于索引的声明,因为我看到你已经创建了它们。

是否有引用“房屋”或被“房屋”引用的表格,它们是否使用延迟加载?

【讨论】:

  • 只有1个表是house,datacontext被重新用于其他查询(10个查询使用相同的datacontext.house)..是的,查询使用延迟加载,查询将仅在调用 .count() 时执行..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多