How to generate unique id in MySQL?

前端 未结 16 2643
生来不讨喜
生来不讨喜 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 04:07

    You may like the way that we do it. I wanted a reversible unique code that looked "random" -a fairly common problem.

    • We take an input number such as 1,942.
    • Left pad it into a string: "0000001942"
    • Put the last two digits onto the front: "4200000019"
    • Convert that into a number: 4,200,000,019

    We now have a number that varies wildly between calls and is guaranteed to be less than 10,000,000,000. Not a bad start.

    • Convert that number to a Base 34 string: "2oevc0b"
    • Replace any zeros with 'y' and any ones with 'z': "2oevcyb"
    • Upshift: "2OEVCYB"

    The reason for choosing base 34 is so that we don't worry about 0/O and 1/l collisions. Now you have a short random-looking key that you can use to look up a LONG database identifier.

提交回复
热议问题