如果我将主键设置为INT
类型(AUTO_INCREMENT
)或设置在UUID
中,这两者在数据库性能(SELECT
、INSERT
等)上有什么区别,为什么?
最佳答案
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
应该使两种选择都与性能相等。请参阅以下引用资料:
- To
UUID
or not toUUID
? - Myths,
GUID
vsAutoincrement
- Performance:
UUID
vsauto-increment
in cakephp-mysql -
UUID
performance in MySQL? - Primary Keys:
ID
s versusGUID
s (coding horror)
(UUID
vs auto-increment
性能结果,改编自 Myths, GUID
vs Autoincrement
)
UUID
优点/缺点(改编自 Primary Keys: ID
s versus GUID
s )
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
ID
s 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
GUID
s 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/