【问题标题】:SQL: Nonclustered index group multiple columns vs single columnsSQL:非聚集索引组多列与单列
【发布时间】:2014-08-25 07:43:23
【问题描述】:

我有表GLTrans,它有一个非聚集索引:

我的查询:

SELECT 
   _glAccount.[Code] as [AccountCode]
   ,_glTrans.[CommentBooking] as [CommentBooking]
FROM 
   [GLTransHeader] _this 
INNER JOIN 
   [GLTrans] _glTrans ON _glTrans.[GLTransHeader_Id] = _this.[Id] 
LEFT INNER JOIN 
   [GLAccount] _glAccount ON _glAccount.[Id] = _glTrans.[GLAccount_Id]
WHERE 
   _glTrans.Folder_Id = '3AFE5BC5-1CC7-4198-9D89-B65591624C6E'

如果我在GLTrans 表中添加Folder_Id,则会显示查询。另一方面,查询超时。

我的问题:

  1. 如果我将键与多列分组,我必须在 where 关键字中使用它们吗?
  2. 如果我为每一列取消分组并创建非聚集索引,它与上面有什么不同吗?

【问题讨论】:

  • 没有LEFT INNER JOIN - 要么是INNER JOIN 要么是LEFT (OUTER) JOIN ......
  • 这个材料已经被报道过很多次了。这个问题太宽泛了。关于索引的基本教程应该比 SO 能更好地回答这个问题。

标签: sql sql-server


【解决方案1】:

Index ON (Col1, Col2) 与 'Index ON (Col2, Col1)` 不同

Index ON (Col1, Col2) 对于以下查询很有用:

Select * 
from YourTable
Where Col1 = ? and Col2 = ?

以及以下查询:

Select *
From YourTable
Where col1 = ?

但对这个查询没有用:

Select *
from YourTable
Where Col2 = ?

索引中列的优先级非常重要。

如果你在select语句中选择列,可以使用include作为索引,换句话说,如果你的索引中没有使用include,sql server使用key lockup来获取数据。

例如下面的查询需要Index on (Col1, Col2) include(Col3)。

Select Col3
from your table
where col1 = ? and col2 = ?

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 2013-08-21
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2017-12-02
    • 2013-08-20
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多