简体   繁体   English

主键的SQL数据类型 - SQL Server?

[英]Sql Data Type for Primary Key - SQL Server?

Which sql data type should we use for number bases primary key: 我们应该使用哪种sql数据类型作为数字基本主键:

  1. int INT
  2. bigint BIGINT
  3. numeric 数字
  4. float 浮动

Generally, int . 通常, int

bigint if you think you'll have more rows than there are atoms in the universe. bigint如果你认为你的行数比宇宙中的原子多。

uniqueidentifier is useful if you need globally unique keys (keys that are guaranteed to be unique across all tables in your schema, maybe even universally unique (I don't remember)) 如果您需要全局唯一键(在模式中的所有表中保证唯一的键,甚至可能是普遍唯一的(我不记得)), uniqueidentifier非常有用

The other two I wouldn't use they're not integral types (they have fractions, which just don't make a lot of sense as keys) 另外两个我不会使用它们不是整数类型(它们有分数,它们作为键没有多大意义)

You really need to keep two separate issues apart: 你真的需要分开两个不同的问题:

1) the primary key is a logical construct - one of the key candidates that uniquely and reliably identifies a row in your table. 1) 主键是一个逻辑结构 - 唯一且可靠地标识表中一行的关键候选之一。 This can be anything, really - an INT, a GUID, a string - pick what makes most sense for your scenario. 这可以是任何东西,真的 - 一个INT,一个GUID,一个字符串 - 选择对你的场景最有意义的东西。

2) the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT or BIGINT as your default option. 2) 聚类键 (在表上定义“聚簇索引”的一列或多列) - 这是一个与物理存储相关的东西,这里,一个小的,稳定的,不断增加的数据类型是你最好的选择 - INT或BIGINT作为默认选项。

By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! 默认情况下,SQL Server表上的主键也用作群集键 - 但这不一定是这样! I've personally seems massive performance gains over time when breaking up the previous GUID-based Primary Clustered Key into two separate key - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1) column. 在将以前的基于GUID的主群集密钥分解为两个单独的密钥 - GUID上的主(逻辑)密钥和单独的INT IDENTITY上的群集(排序)密钥时,我个人似乎随着时间的推移而获得了巨大的性能提升。 ,1)专栏。

The index fragmentation was down to minimal levels, and thus the index seek performance was was up - highly recommended ! 索引碎片降至最低水平,因此索引寻求性能提升 - 强烈推荐!

Marc

One huge reason to not use GUIDs for PKs is their terrible fill ratio for index pages - such misuse can dramatically increase your I/O performance costs. 不使用GUID的一个重要原因是它们对索引页面的填充率很差 - 这种误用可能会大大增加您的I / O性能成本。 GUIDs should be left as AK's and instead drive queries with int-derived PK's wherever possible. GUID应保留为AK,而是尽可能使用int派生的PK驱动查询。

对于32位处理器,int可能是最有效的处理大小。

unsigned int ,其大小符合您的特定需求

GUID / UUID是表的唯一主键的最佳字段类型。

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

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