Trying to generate a unique code to prevent duplicates i use the following query using HAVING clause so i can use the alias but i get duplicate key errors:
SELECT
FLOOR(100 + RAND() * 899) AS random_code
FROM product_codes
HAVING random_code NOT IN (values)
LIMIT 1
The following code did not work and is what i need:
https://stackoverflow.com/a/4382586
Is there a better way to accomplish this or there is something wrong in my query?
Wanted to use a MYSQL query to get random numbers left between 0-999 as a code but tryed that query and also i ended filling the values condition from 0 to 999 and still got always duplicate codes, strange behaviour so i ended up using PHP.
The steps i use now:
Create an array populated with 0 to 999, in the future if i need more codes will use 0 to 9999.
$ary_1 = array(0, 1, 2, …., 999)
Create other array populated with all codes in the table.
$ary_2 = array(4, 5, 985, 963, 589)
Get a resulting array using array_diff.
$ary_3 = array_diff($ary_1, $ary_2)
Get an array key using array_rand from the resulting array_diff.
$new_code_key = array_rand($ary_3, 1)
Use that key to get the code and create the MYSQL query.
$ary_3[$new_code_key]
Unset that key from the new codes array so i speed up the process and just have to get anoher array_rand key and unset later.
unset($ary_3[$new_code_key])