Table of Contents
回复内容:
Home Backend Development PHP Tutorial uuid作为主键,还是用自增呢?

uuid作为主键,还是用自增呢?

Jun 06, 2016 pm 08:09 PM
asp.net java mysql oracle php

我在网上找了好久,有的人说uuid比较好,就是在分库分表,合并数据什么的比较容易,也有的人说自增好,到了表的数据多的时候,性能比uuid好得多,到底那种比较好呢?有没有在真实生产环境的大神,来给出一个完整的解答?

回复内容:

我在网上找了好久,有的人说uuid比较好,就是在分库分表,合并数据什么的比较容易,也有的人说自增好,到了表的数据多的时候,性能比uuid好得多,到底那种比较好呢?有没有在真实生产环境的大神,来给出一个完整的解答?

首先UUID的性能并不比自增ID差很多,这取决于UUID的生成算法。举个例子MongoDB所采用的ObjectId就是一个比较优秀的UUID策略,其组成是时间戳+机器码+进程码+自增数,其中机器码和进程码都可以一次性生成,这样得到一个ObjectId仅仅之比自增ID多了一个时间戳的获取。另外考虑到自增ID都要做主键唯一索引,而UUID可以只做索引,不做唯一索引(利用其特性,可以不考虑唯一性过滤),其性能可以说并不比自增ID差。

至于使用UUID还是自增ID主要还是看项目是否足够庞大,数据量是否足够多。从使用方便性上来说自增ID使用简单,不需要额外支持,而UUID相对麻烦一些,涉及到UUID算法的选取、程序的嵌入等等。而从应对庞大系统的效果上来说,UUID就比自增ID显得优秀得多。怎么选择就是看自己的实际情况,按需选择。

Oracle环境下(其他数据库没有使用经验):
长远来说,自增Number的占用空间比UUID(raw(16)占用32字节)更大,但一般表的数据量在数百亿以内时number占用的空间还是更少;
UUID使用没有number方便,UUID存储为raw(16)时查询条件需要使用HEXTORAW转换;
相同行数情况下,基于UUID的索引占用空间比number更大,数据量上去了读取磁盘次数肯定就更多了;
并发或者rac集群环境下,因为热块现象UUID的性能高于number(建立反向索引可解决这个问题);
UUID使用于前台展示时更安全,Number可以猜测

  1. 如果这个 id 会暴露给用户的话(URL的一部分),那么自增ID 更友好。

  2. 性能方面 2 个差距不太大

  3. 开发方便性的话,UUID 比 自增ID 要方便的多

    • UUID 可以解决分布式ID不冲突,数据库自增ID不支持。

    • UUID 可以在提交数据库之前就获取,不需要多一个 select 语句

    • 不是所有数据库都支持自增ID

  4. UUID可以不采用标准的36位长度,可以用base64压缩到12-16位长度。

  5. 优先采用UUID方案,如果需要更友好的 URL,也应该采用 sequence 代替自增ID

上面大部分答案从开发人员角度比较uuid生成效率,而对数据库的存取效率案例看,用InnoDB或TokuDB的话,答案就是自增主键,看看Oracle ACE的这篇解答:
为什么InnoDB表要建议用自增列做主键

按需所取,具体问题具体分析,简单的说,一般 32字节的UUID 可以通用

自增在索引上有优势(整型的比较比字符串比较要快),但优势有限。两者的区别最主要在于id是在client端/server端生成。 相对于mysql来说,java程序就是一个client端。uuid可以保证client端生成一个唯一且不重复的id,这在分布式系统中非常重要。

如果你摸不准的话,我建议你使用uuid.

这个要看你底层存储的选型,Oracle我不熟,他底层使用rowid来完成,所以不发表评论。其他类似MongoDB等都有自己特殊性,所以用UUID倒反合适。

但如果你的底层存储用MySQL,而且存储引擎又恰好是Innodb,那我是非常推荐你使用唯一自增的数字来作为你的PK;

首先不去探讨UUID和long这两个数据在CPU进行计算时分别对应多少个指令和CPU计算周期,最重要的是Innodb的底层存储是B+Tree,需要按照一个聚集索引,所有的数据查询操作都是基于聚集索引来完成(如果表设计了PK,则聚集索引默认选用就是这个PK)

如果InnoDB表的数据写入顺序能和B+树索引的叶子节点顺序一致的话,这时候存取效率是最高的。

当然了,如果你的系统不追求性能的极限,那随便玩

为什么不定制自己的主键策略呢?

mysql的使用自增的,不然innodb也要自己维护主键索引的。

如果是单机, 推荐使用mysql的自增id.

如果是分布式环境, 想要保持全局的唯一id, 自增和uuid都不行。
这个时候就需要自已定制一套id生成机机制了

【注意】
我遇到过GUID重复,所以,直接用GUID做唯一主键是有潜在问题的!

(GUID是UUID标准的一种实现)

这个感觉还是要看具体的场景吧,如果只是一台数据库服务器的话,并且业务逻辑并不复杂,完全可以使用自增ID的方式,简单开发;如果是仅有少量的几台主数据库服务器也可以使用自增ID,但需要做一些处理。

对于分布式的,也就是有多台主数据库服务器的情况再使用自增ID就会使开发变得复杂,自增ID会变得越来越难控制,这时候何不用UUID呢,毕竟两者的性能也没差多少

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

How to analyze the execution plan of MySQL query How to analyze the execution plan of MySQL query Apr 29, 2025 pm 04:12 PM

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

See all articles