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
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.