select 30 random rows where sum amount = x

前端 未结 7 1355
感情败类
感情败类 2020-12-10 02:39

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

7条回答
  •  时光说笑
    2020-12-10 03:20

    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;
    

提交回复
热议问题