I'm trying to get a unique code number which doesn't exists in the "codes" table using a query I found in several other SO threads:
https://stackoverflow.com/a/25435263/471573 https://stackoverflow.com/a/11680058/471573
I'm currently trying to use this code:
CREATE TABLE codes (
code int NOT NULL
);
INSERT INTO `codes` (`code`) VALUES
(1),(2),(3),(4),(5);
SELECT FLOOR(RAND() * 10) AS `rand_code`
FROM `codes`
WHERE "rand_code" NOT IN (SELECT `code` FROM `codes`)
LIMIT 1
sqlfiddle:
http://sqlfiddle.com/#!9/5e807/2
With lots of issues:
- if no codes are in the table, I get no results at all.
- if there ARE any codes, the results is not unique. I can get a result already in the table...
Any idea on how to make this work?
Thanks!