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

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

    You could do it step by step. Say we have $500 ask limit. First get the min price in your DB.

    select MIN(item_price) from items
    

    Lets say this is 25.00 so for our first item we want a max from 500 plus 2 times the least value (2 * 25 = 50) so i check for the first item matching less or equal to 450 dollars

    select item_id, item_price from items where item_price <= 450 order by rand() limit 1
    

    This item now maybe is 240 dollars, so next query is:

    select item_id, item_price from items where item_price <= 140 order by rand() limit 1
    

    The next one could be 50 dollars, so the next query is:

    select item_id, item_price from items where item_price <= 90 order by rand() limit 1
    

    And there you go.

    I am aware, that this is a quite simple solution and there surely could be better solutions, but using triple joins and random sorting on large tables will swallow lots of performance, and the result of the queries are not better than running these three simple queries, that will run like burst if table is indexed properly.

    Doing it this way also would give you fine control on combinations returned (i.e. you could extend items with categories and reduce queries to distinct categories, so for example you could combine technical+kitchen+fun categories).

    Since we are all here to learn, and we never stop learning, i believe this solution is a good basis for a flexible extension of the functionality. If you want to use a single query, then i would advise to have the query dump a large set of possible combinations into a table, so you can run your massive query maybe once a day and when you want to pick a combination, you just query your pre-rendered random table.

提交回复
热议问题