MySQL Select 3 random rows where sum of three rows is less than value

后端 未结 6 637
庸人自扰
庸人自扰 2021-01-17 22:09

I am trying to select three random rows from a table, where their combined item_price column is less than a desired amount.

Imagine you have an

6条回答
  •  执念已碎
    2021-01-17 22:50

    you can get all triplets of items having sum of price <= 300 with

    SELECT a.item_id, a.item_price, b.item_id, b.item_price, c.item_id, c.item_price
      FROM items a 
           JOIN items b ON a.item_id < b.item_id
           JOIN items c ON b.item_id < c.item_id
     WHERE a.item_price + b.item_price + c.item_price <= 300
    

    then you could sort by rand() and pick one.

    there are discussions about performance of selecting random rows in mysql that you should check. the triple join will be costly if items table is big.

    EDIT

    as suggested in other answers, this query can be improved filtering each item by price <= 300, and using an index on items.price.

提交回复
热议问题