How to generate unique id in MySQL?

前端 未结 16 2623
生来不讨喜
生来不讨喜 2020-11-29 03:17

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.

16条回答
  •  温柔的废话
    2020-11-29 03:57

    A programmatic way can be to:

    • add a UNIQUE INDEX to the field
    • generate a random string in PHP
    • loop in PHP ( while( ! DO_THE_INSERT ) )
      • generate another string

    Note:

    • 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

提交回复
热议问题