简体   繁体   English

我应该为数据库中的 id 使用什么数据类型?

[英]what data type should I use for ids on database?

I saw many debates and articles as to which of integer(increment) and uuid should be used for ids on database.我看到很多关于整数(增量)和 uuid 中的哪一个应该用于数据库中的 id 的辩论和文章。

There introduced some pros and cons of both the integer and uuid.介绍了整数和 uuid 的一些优缺点。

For example, integer: fast, but available size is limited(unless you use bigint) uuid: very unique and much more secure, but slow, and storage- consuming例如,整数:快,但可用大小有限(除非您使用 bigint) uuid:非常独特且更安全,但速度慢且占用存储空间

Then, I wondered if using random strings length of around 10( varchar(10) ), comprised of upper and lower case letters, and integers would solve the problems because they are not so big in size and can cover wide range of data(62^10 ways if 10 chars).然后,我想知道是否使用长度约为 10( varchar(10) )、由大小写字母和整数组成的随机字符串可以解决问题,因为它们的大小不大并且可以覆盖广泛的数据(62 ^10 种方式(如果 10 个字符)。

So, my question is, Is it good or bad to do that?所以,我的问题是,这样做是好是坏?

There is no absolute bad or good when it comes to database design.在数据库设计方面没有绝对的好或坏。 You should design your database based on your needs.您应该根据您的需要设计您的数据库。

You mentioned some pros and cons of using int and uuid and now i recommend you to list your needs so you can choose which one to use.您提到了使用 int 和 uuid 的一些优缺点,现在我建议您列出您的需求,以便您可以选择使用哪一个。

Also keep in mind that you can use some tricks to get around the limits of both ints and uuids.还要记住,您可以使用一些技巧来绕过整数和 uuid 的限制。

For example if uuid seems the right option for you but the speed of looking them up in the database is bothering you, then you can simply use indexing to maximize the speed for uuids.例如,如果 uuid 对您来说似乎是正确的选择,但在数据库中查找它们的速度让您感到困扰,那么您可以简单地使用索引来最大化 uuid 的速度。 and if you have many writes and you need them to be fast, you can use pre-generated uuids.如果你有很多写入并且你需要它们很快,你可以使用预先生成的 uuid。 (generate some uuids, index them, and pick one of them up each time you need to) (生成一些 uuid,索引它们,并在每次需要时选择其中一个)

And for ints, you can simply use 2 ints as your id which both of them together will make the id or some other math algorithm that make it a little more secure but yet fast enough.对于整数,您可以简单地使用 2 个整数作为您的 id,这两个整数一起将构成 id 或其他一些数学算法,使其更安全但足够快。

These are just two example of how you can optimize your system so it will be fast enough and yet answering to your needs in the best way possible.这些只是您如何优化系统的两​​个示例,使其足够快,同时以最佳方式满足您的需求。

And for the case that it is okay to use both ints and uuids in your database design: it is completely ok if it's the best way of doing it for both satisfying your needs and getting the best performance out of it.对于在您的数据库设计中同时使用 int 和 uuid 的情况:如果这是满足您的需求并从中获得最佳性能的最佳方式,那完全没问题。

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

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