mysql - MySQL中INT和UUID的区别

标签 mysql performance primary-key

如果我将主键设置为INT类型(AUTO_INCREMENT)或设置在UUID中,这两者在数据库性能(SELECTINSERT 等)上有什么区别,为什么?

最佳答案

UUID 返回一个 universal unique identifier(如果也导入到另一个数据库,希望也是唯一的)。

引用自 MySQL 文档(强调我的):

A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other.

另一方面,一个简单的 INT 主 ID 键(例如 AUTO_INCREMENT)将为特定的数据库和数据库表返回一个唯一的整数 , 但它并非普遍唯一(因此如果导入到另一个数据库中,可能会出现主键冲突)。

就性能而言,使用 auto-increment 与使用 UUID 应该没有任何明显的区别。大多数帖子(包括本网站作者的一些帖子)都是这样声明的。当然 UUID 可能需要更多的时间(和空间),但这对于大多数(如果不是全部)情况来说并不是性能瓶颈。将一列作为 Primary Key 应该使两种选择都与性能相等。请参阅以下引用资料:

  1. To UUID or not to UUID?
  2. Myths, GUID vs Autoincrement
  3. Performance: UUID vs auto-increment in cakephp-mysql
  4. UUID performance in MySQL?
  5. Primary Keys: IDs versus GUIDs (coding horror)

(UUID vs auto-increment 性能结果,改编自 Myths, GUID vs Autoincrement )

enter image description here

UUID 优点/缺点(改编自 Primary Keys: IDs versus GUIDs )

GUID Pros

  • Unique across every table, every database, every server
  • Allows easy merging of records from different databases
  • Allows easy distribution of databases across multiple servers
  • You can generate IDs anywhere, instead of having to roundtrip to the database
  • Most replication scenarios require GUID columns anyway

GUID Cons

  • It is a whopping 4 times larger than the traditional 4-byte index value; this can have serious performance and storage implications if you're not careful
  • Cumbersome to debug (where userid='{BAE7DF4-DDF-3RG-5TY3E3RF456AS10}')
  • The generated GUIDs should be partially sequential for best performance (eg, newsequentialid() on SQL 2005) and to enable use of clustered indexes.

注意事项

我会仔细阅读提到的引用资料,并根据我的用例决定是否使用 UUID。也就是说,在许多情况下,UUID 确实更可取。例如,可以在根本不使用/访问数据库的情况下生成 UUID,甚至可以使用已经预先计算和/或存储在其他地方的 UUID。此外,您可以轻松地概括/更新您的数据库架构和/或集群方案,而不必担心 ID 中断并导致冲突。

在可能的冲突方面,例如使用v4 UUIDS(随机),the probability to find a duplicate within 103 trillion version-4 UUIDs is one in a billion.

关于mysql - MySQL中INT和UUID的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30461895/

相关文章:

php - 如何在mysql查询中查找和替换字符串

database - Mysqldump 创建部分备份

c# - View 会降低 LINQ 查询性能吗?

MySQL 更新 AUTO_INCRMENT pk 以保留行排序

entity-framework - 如何在 Entity Framework (.Net 4.0) 中使用导航属性作为主键?

c# - 如何查看哪些文档已打开?

Java加载图像更快

java - 有效地对逻辑上属于同一实体的对象列表进行排序

sql - 在数据库外存储主键生成器的安全方法?

php - 我可以用程序风格编写准备好的陈述吗?