I have this two querys that I think should behave the same way but they do not.
Query 1 (Always return empty):
SELECT * FROM code
WHERE id = (
SELECT id FROM code
WHERE available = 1
ORDER BY rand()
LIMIT 1
)
FOR UPDATE SKIP LOCKED;
Query 2 (Return one random row where available = 1
):
SELECT * FROM code
WHERE id = (
SELECT rc.id FROM
(
SELECT id FROM code
WHERE available = 1
ORDER BY rand()
LIMIT 1
) as rc
)
FOR UPDATE SKIP LOCKED;
If I run the subquerys independently they behave the same (Return one random row where available = 1
)
Example:
SELECT rc.id FROM
(
SELECT id FROM code
WHERE available = 1
ORDER BY rand()
LIMIT 1
) as rc;
-- returns 1 row
--
-- id
-- 1 <random_id>
SELECT id FROM code
WHERE available = 1
ORDER BY rand()
LIMIT 1
-- returns 1 row
--
-- id
-- 1 <random_id>
Table code
definiton:
CREATE TABLE `code` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`available` tinyint(4) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
);
I tried both querys but get empty result for the first query and the second gives the expected result. As far as i know they should return the same result, what I am missing?