I want to generate a unique random integer (from 10000 to 99999) identity just by clean mySQL; any ideas?
I don't want to generate this number in php by cycling (generate number -> check it in database) because I want to use some intelligent solution in a mySQL query.
In MySQL, UUID() function returns Universal Unique Identifier that generates 36 characters long value which is 5 part hexadecimal numbers. If you want to generate random password, you can make use of this function which generate random number.
We can generate UUID values in MySQL using the function as follows: mysql> SELECT UUID();
The NEWID() function will generate a unique identifier(alpha-numeric) on each execution. This is the logical id format that uses to assign to each record across the Servers/Databases by the SQL SERVER. Random Number : The RAND() function will generate a unique random number between 0 and 1 on each execution.
The uniqid() function generates a unique ID based on the microtime (the current time in microseconds). Note: The generated ID from this function does not guarantee uniqueness of the return value! To generate an extremely difficult to predict ID, use the md5() function.
While it seems somewhat awkward, this is what can be done to achieve the goal:
SELECT FLOOR(10000 + RAND() * 89999) AS random_number
FROM table
WHERE random_number NOT IN (SELECT unique_id FROM table)
LIMIT 1
Simply put, it generates N random numbers, where N is the count of table rows, filters out those already present in the table, and limits the remaining set to one.
It could be somewhat slow on large tables. To speed things up, you could create a view from these unique ids, and use it instead of nested select statement.
EDIT: removed quotes
Build a look-up table from sequential numbers to randomised id values in range 1 to 1M:
create table seed ( i int not null auto_increment primary key );
insert into seed values (NULL),(NULL),(NULL),(NULL),(NULL),
(NULL),(NULL),(NULL),(NULL),(NULL);
insert into seed select NULL from seed s1, seed s2, seed s3, seed s4, seed s5, seed s6;
delete from seed where i < 100000;
create table idmap ( n int not null auto_increment primary key, id int not null );
insert into idmap select NULL, i from seed order by rand();
drop table seed;
select * from idmap limit 10;
+----+--------+
| n | id |
+----+--------+
| 1 | 678744 |
| 2 | 338234 |
| 3 | 469412 |
| 4 | 825481 |
| 5 | 769641 |
| 6 | 680909 |
| 7 | 470672 |
| 8 | 574313 |
| 9 | 483113 |
| 10 | 824655 |
+----+--------+
10 rows in set (0.00 sec)
(This all takes about 30 seconds to run on my laptop. You would only need to do this once for each sequence.)
Now you have the mapping, just keep track of how many have been used (a counter or auto_increment key field in another table).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With