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

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

    I was able to get the result with both these queries and a PHP version below

    SET @MaxAmount = 5;
    SELECT FirstItem.id, SecondItem.id, ThirdItem.id, FirstItem.amount +  SecondItem.amount +  ThirdItem.amount as Total
    FROM Items as FirstItem
    CROSS JOIN Items as SecondItem  ON SecondItem.id <> FirstItem.id and FirstItem.amount + SecondItem.amount < @MaxAmount 
    CROSS JOIN Items as ThirdItem ON ThirdItem.id <> FirstItem.id  and ThirdItem.id <> SecondItem.id and FirstItem.amount + SecondItem.amount + ThirdItem.amount < @MaxAmount
    ORDER BY RAND()
    LIMIT 3;
    

    And

    SET @MaxAmount = 5;
    SELECT FirstItem.id as id1, SecondItem.id as id2, ThirdItem.id as i3,  FirstItem.amount +  SecondItem.amount +  ThirdItem.amount as Total 
    FROM Items FirstItem, Items SecondItem, Items ThirdItem
    WHERE FirstItem.amount + SecondItem.amount < @MaxAmount
    AND FirstItem.amount + SecondItem.amount  + ThirdItem.amount < @MaxAmount
    AND SecondItem.id != FirstItem.id -- Prevent Same Id from showing up
    AND ThirdItem.id != FirstItem.id  and ThirdItem.id != SecondItem.id
    ORDER BY RAND()
    LIMIT 3;
    

    http://sqlfiddle.com/#!9/0e1c8/3

    I would only do this if the Items table is relatively small. You can do this in PHP by selecting all the items with the price less than 300 and generating the k combinations(also named nCr) of 3 and then using a filter function that returns the ones that summed together are less than 300.

    $rows = $db->query("Select FirstItem.amount as amount1, SecondItem.amount as amount2, ThirdItem.amount as amount3 (.. and also the ids) from Items where amount < 300");
    $ncr = getCombinations($rows, 3);
    $filtered = array_filter($ncr, function($row) { return $row['amount1'] + $row['amount2'] + $row['amount3'] < 300; })
    

提交回复
热议问题