简体   繁体   English

即使表仅包含一列并且表本身包含唯一值,使用代理主键也是一种好习惯吗?

[英]Is it a good practice to use surrogate primary key even if the table contains only one column and that itself contains the unique values?

I am having a gender table as: gender_id | gender_label 我的gender表为: gender_id | gender_label gender_id | gender_label
Will it be a bad practice if I remove the gender_id column, as gender_label is also unique and can be used as a primary key? 如果我删除了gender_id列,这是一个不好的做法,因为gender_label也是唯一的并且可以用作主键?
I know surrogate keys should be used wherever possible as they are efficient and fast to search. 我知道应该尽可能使用代理键,因为它们高效且快速地搜索。 But will it make any difference for above scenario? 但这对上述情况有什么影响吗? How? 怎么样?

I have written hundreds of tables. 我写了几百张桌子。 2/3 of them have a "natural" key; 其中2/3具有“自然”键; 1/3 have a "surrogate key". 1/3有一个“代理钥匙”。

From that, I deduce that the answer to your question is "it depends". 由此,我推断出您问题的答案是“取决于”。

OK, so what does it depend on? 好的,那取决于什么?

  • Is there a reliable natural key -- one that is truly UNIQUE ? 是否有可靠的自然钥匙-真正UNIQUE钥匙? If so, probably you should use it. 如果是这样, 可能您应该使用它。
  • Is performance an issue -- Well, this goes both ways. 性能是一个问题吗?嗯,这是双向的。
  • Is the natural key "small"? 自然键是“小”吗? A 2-character country_code taken from an international standard is, in my opinion, better than a 4-byte INT . 我认为,从国际标准中提取的2个字符的country_code优于4字节的INT
  • If the natural key is "big" and there are multiple secondary keys, then keep in mind that the PK is included in every secondary key. 如果自然键为“大”并且有多个辅助键,则请记住,每个辅助键都包含PK。 (In InnoDB) (在InnoDB中)
  • A lookup by a secondary key involves (in InnoDB) first a drill-down in the secondary key's BTree, then a drill-down in the PK's BTree. 通过辅助键进行查找涉及(在InnoDB中),首先在辅助键的BTree中进行向下钻取,然后在PK的BTree中进行向下钻取。 So, there is a slight-to-large performance benefit in having a PK that you use a lot. 因此,拥有大量使用的PK可能会带来轻微的性能提升。 (That might be surrogate or it might be natural.) (这可能是替代的,也可能是自然的。)

In your simple case, is gender_id strings like M/F/etc? 在您的简单情况下,是否像M / F / etc这样的gender_id字符串? That's what I would use. 那就是我会用的。 Actually, I might not have the table at all; 实际上,我可能根本没有桌子。 instead have gender in other tables as ENUM('unknown', 'male', 'female', 'other') 而是在其他表格中使用gender作为ENUM('unknown', 'male', 'female', 'other')

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

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