mysql数据库,如何使用uuid代替id做数据表的主键?
发布于 作者:苏南大叔 来源:程序如此灵动~

本文聊聊在mysql
中如何使用uuid
作为主键。当然,一般情况下,是使用自增一的id
字段作为主键的。随着目前数据库的体量的不断增大,使用uuid
做主键的数据表也不断增多。
大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔的代码经验所学所想。测试环境:win10
,mysql@5.7.26
。
uuid
格式
mysql
中的uuid()
获得是一个用中划线链接的36位的字符串。类似如下:
0a9497de-1e09-11ee-a41f-34363b67eb71
在前面的文章里面,苏南大叔还写过一个nodejs
下的uuid()
。链接如下:
mysql
的uuid()
结果和nodejs
的uuid()
的第四版结果非常类似。
mysql
语句中获得uuid
可以执行下面的语句,获得uuid()
,多次执行的时候,每次执行的结果都是不一样的。
select uuid();
如果要获得不带中划线的uuid()
,可以使用内置的replace()
函数。
select replace(uuid(), '-', '');
作为主键插入uuid
这里uuid
字段作为主键:
CREATE TABLE `users2` (
`uuid` varchar(36) NOT NULL DEFAULT '',
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`uuid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
insert into users2( uuid,name ) values( uuid(), "苏南大叔" );
相关链接
- https://newsn.net/say/node-uuid.html
- https://newsn.net/say/node-nanoid.html
- https://newsn.net/say/mysql-null.html
总结
表面上来看,uuid()
必然是不重复的。但是,理论上来说,是存在非常微小的概率重复的。更多mysql
数据库经验文章,请点击苏南大叔的经验文章:


