Skip to content

Instantly share code, notes, and snippets.

@mfr
Created October 10, 2011 13:45
Show Gist options
  • Save mfr/1275370 to your computer and use it in GitHub Desktop.
Save mfr/1275370 to your computer and use it in GitHub Desktop.
MySQL selecting random rows fast
SELECT *
FROM (
SELECT @cnt := COUNT(*) + 1,
@lim := 10
FROM t_random
) vars
STRAIGHT_JOIN
(
SELECT r.*,
@lim := @lim - 1
FROM t_random r
WHERE (@cnt := @cnt - 1)
AND RAND() < @lim / @cnt
) i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment