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
Here's a SQL only (MySQL flavour) solution:
SELECT i.*
FROM items i
CROSS JOIN
(SELECT CONCAT('^(', t1.item_id, '|', t2.item_id, '|', t3.item_id, ')$') AS regex
FROM items t1
CROSS JOIN items t2
CROSS JOIN items t3
WHERE t1.item_id < t2.item_id
AND t2.item_id < t3.item_id
AND t1.item_price + t2.item_price + t3.item_price <= 300
ORDER BY RAND()
LIMIT 1) s
WHERE i.item_id REGEXP s.regex
Not very efficient for large result sets as it creates a subquery of the different permutations of 3 items that fulfill the total criteria and then picks one of these at random. The subquery returns its result as a regular expression to allow the rows to be picked in the outer query.
See SQL Fiddle demo.