数据库-字符串作为主键? [英] Databases - String as Primary key?
问题描述
我使用Laravel 5开发了一个应用程序,并在开发过程中使用了sqlite.我想稍后再切换到更快的速度.我想要一个字符串作为用户表的唯一标识符.这有什么问题吗?例如带有外键?还是自动递增整数没有区别?
I develop an application with Laravel 5 and use sqlite during development. I want to switch to something faster later on. I'd like to have a string as unique identifier for the users-table. Is this a problem in any way? For example with foreign keys? Or is there no difference to auto-increment integers?
推荐答案
简短的答案:将字符串用作主键是完全可以的.
The short answer : It's perfectly fine to use a string as a primary key.
长答案:选择字符串作为主键很可怕.
The long answer : We are terrible at choosing strings to be primary keys.
什么是好的主键候选者?
What is a good primary key candidate ?
- 它应该是唯一的.
- 应该很少更改(如果有的话).
现在,您可能会认为您的字符串永远不会改变,并且它是极其独特的,直到不再变得独特为止.
Now, You are probably thinking that your string would never change, and that it's extremely unique, Until it will stop being unique.
另一个(次要)问题是性能.在整数上的搜索,连接等比在字符串上要快一些,这主要是由于长度(数字通常比字符串短,因此比较容易).
Another (minor) concern, is performance. Searching, Joining etc. is a bit faster on integers than on strings, mostly due to the length(numbers are normaly shorter than strings, so comparing is easier).
在主键上使用什么字符串时,我会花很长时间思考,在大多数情况下,这是个坏主意
I would think long and hard on what string to use on the primary key, Most of the times it's a bad idea
这篇关于数据库-字符串作为主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!