jeudi 24 janvier 2019

How to create randomized user ids with no repeats in MySQL?

I am looking for some insight into efficiency and ease of implementation with a certain goal I have. I have a MySQL table storing user information. When an account is created, they need to get their own unique random 5 digit code from 00000-99999.

Here are the strategies I am considering. Some of them seem difficult (for a beginner like me), so I just want to consult Stack Overflow for any advice.

  • Populate the company_id column with all 5 digit codes from 00000-99999 in random order. This is what I have done thus far. My issue is that when someone creates an account, I would need to query the database to find the first open row and grab the 5 digit code associated with it. I haven't been able to figure that part out thus far.
  • Populate the company_id column with all 5 digits codes from 00000-99999 in numerical order. When someone creates an account, I would choose a random open row and grab the 5 digit code associated with it. The issue here is choosing a random row that is open. Again, I do not know how I would accomplish this.
  • Create the 5 digit code when the user creates a new account and create a new row in my user_data with that 5 digit code as the company_id column. The issue here is that the program in which a new account is created must be able to access a list of 5 digit codes that are not yet used. I am thinking this may be the best option, by creating an array of 5 digit codes 00000-99999, filling an array with all currently used 5 digit codes from the company_id column, removing all elements in the first array that match elements in the second, and then selecting a random 5 digit code from the altered first array.

What I am asking is which (of these or your own strategy) would be best first and foremost in terms of efficiency when creating a new account (don't want to keep users waiting), and secondly, in terms of ease of implementation. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire