【问题标题】:difference between creating index with two columns and creating separate index on two columns用两列创建索引和在两列上创建单独索引之间的区别
【发布时间】:2014-08-25 09:57:12
【问题描述】:

用两列创建索引和在两列上创建单独索引有什么区别?

区别

create nonclustered index ix_index1 on table1(col1)
create nonclustered index ix_index2 on table1(col2)

create nonclustered index ix_index1 on table1(col1, col2)

【问题讨论】:

    标签: sql sql-server sql-server-2008 indexing non-clustered-index


    【解决方案1】:

    如果您有任何仅基于col2 选择的查询,您可能会遇到不同。

    SELECT (list of columns)
    FROM dbo.YourTable
    WHERE col2 = 'someValue'
    

    如果您有两个单独的索引,则有可能使用ix_index2 来加快此查询的速度。

    但是,如果您在 (col1, col2) 上只有一个复合索引,则该索引永远不能用于此查询。 只有在查询中引用了最左边的n列时才能使用复合索引。

    所以你的复合索引可能会被使用

    • 如果您的查询在WHERE 子句中同时使用col1col2
    • 如果您的查询在 WHERE 子句中仅使用 col1

    但如果您的查询仅在WHERE 子句中使用col2,则可以绝不使用它

    【讨论】:

    • 如果查询根本不使用 where 子句怎么办?
    • 那么你的索引就完全没用了(除非你使用的 ORDER BY 子句使用了这些列之一或两者)
    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2011-07-01
    • 2016-09-03
    • 2016-01-10
    • 1970-01-01
    • 2019-02-27
    • 2020-07-24
    相关资源
    最近更新 更多