I have a table
items
id int unsigned auto_increment primary key,
name varchar(255)
price DECIMAL(6,2)
I want to get at least 30 random ite
If you read the MySQL manual you might have seen the ORDER BY RAND() to randomize the the rows.
This example works fine and is fast if you only when let's say 1000 rows. As soon as you have 10000 rows the overhead for sorting the rows becomes important. Don't forget: we only sort to throw nearly all the rows away.
A great post handling several cases, from simple, to gaps, to non-uniform with gaps.
Here is how you can do it perfectly :
SELECT id, name, price
FROM `items` AS i1 JOIN
(SELECT CEIL(RAND() *
(SELECT MAX(id)
FROM `items`)) AS id) AS i2
WHERE i1.id >= i2.id AND i1.price = 500
ORDER BY i1.id ASC
LIMIT 30;