简体   繁体   English

参考列上的数据库聚集索引

[英]Database clustered Index on referring column

I have two tables like this. 我有两个这样的桌子。

Table A 表A

A_ID ( Primary Key) A_ID(主键)
A1 A1
A2 A2

Table B 表B

B_ID ( Primary Key) B_ID(主键)
B1 B1
B2 A_ID ( foreign key but not enforced in database, not unique ) B2 A_ID(外键,但未在数据库中强制执行,不是唯一的)

Although by default SQL server creates clustered indexes on B_ID, I have lot of select queries on B, which depend on A_ID 尽管默认情况下,SQL Server在B_ID上创建聚簇索引,但是我在B上有很多选择查询,这取决于A_ID

something like this 像这样的东西

SELECT * FROM B WHERE B.A_ID = 'SOME ID' SELECT * FROM B WHERE B.A_ID ='SOME ID'

Should I be creating clustered Index on A_ID of TABLE B ? 我应该在表B的A_ID上创建聚簇索引吗?

No, just create a normal non-clustered index - you'll have basically the same results and same improvements in your query speed. 不,只需创建一个普通的非聚集索引-您将获得基本相同的结果,并且查询速度得到了相同的改进。

Is the A_ID on table B even guaranteed to be unique?? 表B上的A_ID甚至可以保证是唯一的吗? Couldn't more than 1 entry in "B" reference the same A_ID ?? 引用同一A_ID的条目不能超过1个?

Best practice for a clustered key is: 集群密钥的最佳实践是:

  • as small as possible (narrow) 尽可能小(窄)
  • unique 独特
  • stable (or static - it should never change) 稳定(或静态-它永远不会改变)
  • ever increasing 不断增加

See Kim Tripp's The Clustered Index Debate continues or Ever-increasing clustering key - the Clustered Index Debate - agin! 请参见Kim Tripp的“聚簇索引辩论继续进行”聚类密钥不断增加-聚簇索引辩论-重新开始! for additional info. 有关其他信息。

If your clustered key cannot be guaranteed to be unique, SQL Server will add a 4-byte uniquifier to it - you'll want to avoid that whenever possible (because your clustering key will be added to every single entry of every single non-clustered index on your table, leading to waste of space if it's too wide). 如果不能保证群集键的唯一性,则SQL Server将在其中添加一个4字节的唯一化符-您将尽可能避免这种情况(因为您的群集键将被添加到每个非群集的每个条目中)表上的索引,如果索引太宽,则会浪费空间)。

Marc

No a regular non-clustered index should do fine. 常规的非聚集索引都不能正常工作。 A clustered index is especially handy when doing range queries (BETWEEN) As a rule of thumb I always create non-clustered indexes on columns used in foreign key constraints. 进行范围查询时(聚集),聚集索引特别方便(根据经验),我总是在外键约束中使用的列上创建非聚集索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM