MYSQL generate a unique random-looking number without using PHP loops

QuestionsMYSQL generate a unique random-looking number without using PHP loops
sethbeckerman5 Staff asked 4 years ago

Without using PHP loops, I'm trying to find an efficent way to generate a unique number that's different from all existing values in MYSQL database. I tried to do that in PHP, but it's not efficent because it has to deal with lots of loops in the future. Recently, I tried to do this with MYSQL and I found this sqlfiddle solution. But It doesn't work. Sometimes it generates the same number as in the table and it doesn't check every value in the table. I tried this this but didn't help. They generally give that query:

I will work with 6-digit numbers in the future, so I need that to be efficent and fast. I can use different methods such as pre-generating the numbers to be more efficent but I don't know how to handle that. I would be glad if you help.
EDIT: Based on @Wiimm's solution, I can fill the table with 999.999 different 'random' unique numbers without using PHP loop functions. Then I developed a method where ID's of the deleted rows can be reused. This is how I managed it:

Duplicate your original table and name it "table_deleted". (All columns must be the same.)
Create a trigger in MYSQL. To do that, enter "SQL" in MYSQL and run this code (It simply moves your row to the "table_deleted"):

MYSQL Code

Create another trigger. This code will move the row back to original table when it's updated.

MYSQL Code

The PHP code that I use (The number column must be "NULL" to work this code):

PHP Code

MYSQL triggers do the rest for you.


View on Stack Overflow