正确的数据库索引用于排序查询

时间:2015-10-14 13:03:49

标签: c# sql-server indexing linq-to-sql

我有一张桌子:

Tutorials
-------
ID
Deleted
CategoryID
DifficultyID
Videos
TotalVisitors
DateCreated

在我的网页上,过滤这些教程的查询构建如下:

var q = db.Tutorials.Where(c => !c.Deleted);

if (Category != null) q = q.Where(c => c.CategoryID == Category.ID);

if (Difficulty != null) q = q.Where(c => c.DifficultyID == Difficulty.ID);

if (OnlyWithVideos) q = q.Where(c => c.Videos > 0);

if (sortMethod != null)
{
    if (sortMethod == SortMethod.MostPopular)
        q = q.OrderByDescending(c => c.TotalVisitors);
    else if (sortMethod == SortMethod.Newest)
        q = q.OrderByDescending(c => c.DateCreated);
}

然后我在表上创建以下单个索引:

Deleted ASC
CategoryID ASC    
DifficultyID ASC
Videos ASC
TotalVisitors ASC
DateCreated ASC

我的问题是:

  • 此索引是否涵盖所有可能的查询,还是我需要为每个可能的搜索创建索引?
  • 索引的列顺序是否重要?
  • 每列的ASC / DESC订单是否重要?

1 个答案:

答案 0 :(得分:0)

首先,没有必要为每个可能的查询都有一个索引。在许多情况下,没有指数更好。此外,索引性能还取决于数据的选择性。例如,如果您只有两个可能的值,那么索引就不会有太大帮助。 我建议在SQL Server管理工具中查看Explain Plain(或Estimation Plan),以帮助您找出最有效的方法。创建索引并查看不同查询的执行方式。 此外,列顺序在覆盖索引中很重要:它应该与您查询列的顺序相对应。

相关问题