MySQL UUID 主键 - 由 PHP 还是 MySQL 生成?
我的印象是,只要让 MySQL 通过 UUID()
生成主键就会使该键在服务器等之间唯一。
但是,无法获取最后插入的UUID,这需要每次插入时都执行额外的select语句。
是否可以让 PHP 生成与 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.
But, there is no way to fetch the last inserted UUID, which requires that an extra select statement be done each time I insert.
Is it possible to have PHP generate the exact same UUID()
that MySQL would generate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,PHP 不可能生成与 MySQL 完全相同的
UUID()
,因为它是一个(完全)随机数。听起来您的问题是您喜欢在 MySQL 中使用
UUID()
但不想执行额外的查询来找出新的UUID
是什么。那么为什么不让 PHP 创建
UUID
用作INSERT
查询中的主键呢? php.net 上的此评论 应该向您展示如何执行此操作。使用这些示例函数:
编辑:该页面上有多种方法可以生成不同类型的
UUID
。v4
是伪随机的,但您可以使用不同的版本或创建自己的UUID
生成器。No, it's not possible to have PHP generate the exact same
UUID()
as MySQL because it's a (completely) random number.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 newUUID
is.So why not have PHP create the
UUID
to be used as the primary key in yourINSERT
query?? This comment on php.net should show you how to do this.Using those sample functions:
Edit: There are several methods on that page which generate different types of
UUID
s.v4
is pseudo-random, but you could use a different version or create your ownUUID
generator.根据您的具体情况,我可能会使用存储过程。
这样,您可以
UUID()
,INSERT
语句SELECT
该变量Depending on your exact szenario, I would probbably use a stored procedure.
That way, you can
UUID()
,INSERT
statementSELECT
the variable我尝试了第一步:
$uuid = UUID::v4();
但它挂起了我的服务器,所以我想到了另一个想法,我尝试如下:从查询中获取数据
$sql1 = SELECT UUID() AS uuid ;
然后存储在变量
$uuid
中,然后在下面使用
I tried the first step:
$uuid = UUID::v4();
but it hung my server, so another idea came to mind which I tried as follows:fetch data from query
$sql1 = SELECT UUID() AS uuid ;
then store in variable
$uuid
and then use below