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

后端 未结 6 666
庸人自扰
庸人自扰 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:42

    Another solution i get by looking Lashane's answer because each of the item's price must not be greater than the total. There should be some improvement by adding this (try EXPLAIN to the query).

    SELECT t1.item_id as id1, t2.item_id as id2, t3.item_id as i3
    FROM items t1, items t2, items t3
    WHERE
    t1.item_price <= 300 AND
    t2.item_price <= 300 AND
    t3.item_price <= 300 AND
    t1.item_id <> t2.item_id AND
    t1.item_id <> t3.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
    

提交回复
热议问题