MySQL UUID主键-由PHP或MySQL生成? [英] MySQL UUID primary key - generated by PHP or by MySQL?

查看:306
本文介绍了MySQL UUID主键-由PHP或MySQL生成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给我的印象是,仅让MySQL通过UUID()生成主键,将使该键在服务器等之间都是唯一的.

I was under the impression that just having MySQL generate the primary key via UUID() would make the key unique across servers, etc.

但是,无法获取最后插入的方法UUID ,它要求每次插入时都要执行一个额外的select语句.

But, there is no way to fetch the last inserted UUID, which requires that an extra select statement be done each time I insert.

是否可以让PHP生成与MySQL生成的完全相同的UUID()?

Is it possible to have PHP generate the exact same UUID() that MySQL would generate?

推荐答案

不,因为它是一个(完全)随机数,所以不可能让PHP生成与MySQL完全相同的UUID().

No, it's not possible to have PHP generate the exact same UUID() as MySQL because it's a (completely) random number.

听起来您的问题是您喜欢在MySQL中使用UUID(),但又不想执行额外的查询来确定新的UUID是什么.

It sounds like your problem is that you like using UUID() in MySQL but don't want to execute an extra query to figure out what the new UUID is.

那么为什么不让PHP创建UUID用作INSERT查询中的主键呢? 对php.net的评论应向您展示如何执行此操作

So why not have PHP create the UUID to be used as the primary key in your INSERT query?? This comment on php.net should show you how to do this.

使用这些示例函数:

$uuid = UUID::v4();
$sql = "INSERT INTO mytable (uuid, foo) VALUES ('{$uuid}', 'bar');";
echo "The UUID is: ". $uuid;

编辑:该页面上有几种方法可以生成不同类型的UUID. v4是伪随机的,但是您可以使用其他版本或创建自己的UUID生成器.

Edit: There are several methods on that page which generate different types of UUIDs. v4 is pseudo-random, but you could use a different version or create your own UUID generator.

这篇关于MySQL UUID主键-由PHP或MySQL生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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