如何在MySQL中生成唯一ID? [英] How to generate unique id in MySQL?

查看:786
本文介绍了如何在MySQL中生成唯一ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和MySQL编写脚本,我想获得一个 唯一ID(由字符串组成:大写和小写) 带数字的字母),例如:gHYtUUi5b. 我在PHP中发现了许多可以生成此类数字的函数,但我担心如何确保id唯一!

I'm programming a script using PHP and MySQL and I want to get a unique id (consisting of a string: capitals and small letters with numbers) like: gHYtUUi5b. I found many functions in PHP that can generate such numbers but I'm afraid about how to ensure the id is unique!

更新:uuid很长,我的意思是这样的ID,例如:(P5Dc)一个11个字母数字的字符.

UPDATE: uuid is long, I mean such id like: (P5Dc) an 11 alphanumeric char.

推荐答案

一种编程方式可以是:

  • 在字段中添加一个唯一索引
  • 在PHP中生成随机字符串
  • 在PHP中循环(while(!DO_THE_INSERT))
    • 生成另一个字符串
    • add a UNIQUE INDEX to the field
    • generate a random string in PHP
    • loop in PHP ( while( ! DO_THE_INSERT ) )
      • generate another string

      注意:

      Note:

      • 这可能很脏,但是具有与DBMS无关
      • 的优势
      • 即使您选择使用特定于DBMS的唯一ID生成器功能(UUID等) 最佳做法是使用索引确保字段具有唯一性
      • 统计上根本不执行循环,仅在插入失败时才进入循环
      • This can be dirty, but has the advantage to be DBMS-agnostic
      • Even if you choose to use a DBMS specific unique ID generator function (UUID, etc) it is a best practice to assure the field HAS to be UNIQUE, using the index
      • the loop is statistically not executed at all, it is entered only on insert failure

      这篇关于如何在MySQL中生成唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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