Skip to content

Instantly share code, notes, and snippets.

@Bat-Chat
Last active September 8, 2016 22:38
Show Gist options
  • Save Bat-Chat/dcf86f3b521fd2b45dfa to your computer and use it in GitHub Desktop.
Save Bat-Chat/dcf86f3b521fd2b45dfa to your computer and use it in GitHub Desktop.
little random ids with limit in one query
"SELECT b.id, b.title
FROM books AS b
JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM books)) AS rid)
AS rid2
JOIN books_genres
ON books_genres.book_id = b.id
WHERE b.id >= rid2.rid AND b.id <> $bookId
ORDER BY rid2.rid ASC
LIMIT $limit"
SELECT *
FROM random, (
SELECT id AS sid
FROM random
ORDER BY RAND( )
LIMIT 10
) tmp
WHERE random.id = tmp.sid;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment