[英]MySQL UUID primary key - generated by PHP or by MySQL?
I was under the impression that just having MySQL generate the primary key via UUID()
would make the key unique across servers, etc. 我的印象是,让MySQL通过
UUID()
生成主键会使密钥在服务器等之间是唯一的。
But, there is no way to fetch the last inserted UUID , which requires that an extra select statement be done each time I insert. 但是, 无法获取最后插入的UUID ,这需要每次插入时都执行额外的select语句。
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. 不,PHP不可能生成与MySQL完全相同的
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. 听起来你的问题是你喜欢在MySQL中使用
UUID()
但不想执行额外的查询来弄清楚新的UUID
是什么。
So why not have PHP create the UUID
to be used as the primary key in your INSERT
query?? 那么为什么不让PHP创建
UUID
来用作INSERT
查询中的主键? This comment on php.net should show you how to do this. 这个关于php.net的评论应该告诉你如何做到这一点。
Using those sample functions: 使用这些示例函数:
$uuid = UUID::v4();
$sql = "INSERT INTO mytable (uuid, foo) VALUES ('{$uuid}', 'bar');";
echo "The UUID is: ". $uuid;
Edit : There are several methods on that page which generate different types of UUID
s. 编辑 :该页面上有几种方法可生成不同类型的
UUID
。 v4
is pseudo-random, but you could use a different version or create your own UUID
generator. v4
是伪随机的,但您可以使用不同的版本或创建自己的UUID
生成器。
I tried the first step: $uuid = UUID::v4();
我尝试了第一步:
$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 ;
从查询中获取数据
$sql1 = SELECT UUID() AS uuid ;
then store in variable $uuid
然后存储在变量
$uuid
and then use below 然后在下面使用
$sql = "INSERT INTO mytable (uuid, foo) VALUES ('{$uuid}', 'bar');";
echo "The UUID is: ". $uuid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.