MySQL中的主键:INT(n)或UUID为varchar(36) [英] Primary key in MySQL: INT(n) or UUID as varchar(36)

查看:510
本文介绍了MySQL中的主键:INT(n)或UUID为varchar(36)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MySQL中使用UUID作为主键有意义吗?

Does it make sense to use UUID as primary key in MySQL?

除了手动查询的麻烦之外,使用UUID代替常规INT有什么利弊?

What would be pros and cons of using UUID instead of regular INT, beside trouble of hand querying?

推荐答案

UUID的主要缺点是,如果要稍后再引用该记录以进行进一步使用(例如,在其中添加子记录,则必须先创建它们).依赖的外键表):

The major downside of UUIDs is that you have to create them beforehand if you want to refer back to the record for further usage afterwards (ie: adding child records in dependent foreign keyed tables):

INSERT INTO table (uuidfield, someotherfield) VALUES (uuid(), 'test'));

不会让您看到新的UUID值,并且由于您没有使用常规的auto_incremented主键,因此无法使用last_insert_id()来检索它.您必须分两步进行:

will not let you see what the new UUID value is, and since you're not using a regular auto_incremented primary key, you can't use last_insert_id() to retrieve it. You'd have to do it in a two-step process:

SELECT @newuid := uuid();
INSERT INTO table (uuidfield, someotherfield) VALUES (@newuid, 'test');
INSERT INTO childtable ..... VALUES (@newuid, ....);

这篇关于MySQL中的主键:INT(n)或UUID为varchar(36)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆