what is the best way to create random mysql ID usi

2019-08-08 07:35发布

问题:

i'm building an application that needs a random unique id for each user not a sequence

mysql database

ID   Username

for my unique random ID, what is the best way to do that?

回答1:

PHP provides a uniqid function, which might do the trick, I suppose.

Note it's returning a string, though, and not an integer.


Another idea would be to generate / use some GUID -- there are some proposals about that in the user notes of the manual page of uniqid.



回答2:

I would still have the normal auto-increment primary key to identify each row properly, it's just standard convention.

I'd then have another indexed column called 'user_id' or something and use uniqid(); for it.



回答3:

MySQL provides a function called UUID():

http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_uuid

Documentation claims this:

A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other.

This should cover your needs.



标签: php mysql random