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

后端 未结 6 680
庸人自扰
庸人自扰 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条回答
  •  萌比男神i
    2021-01-17 22:58

    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.

提交回复
热议问题