mysql - HAVING clause and performance -


i've got performance problem sql (mysql) query. have table similar this:

id   price    id  object ----------------------------- 1    500.00   1   1 2    300.00   1   1 3    400.00   1   1 4    100.00   1   1 5    100.00   1   1 6    100.00   2   3 

and need maximum amount of lines given amount.

for example, given amount 1000.00 query must returns these ids (order price asc) , total price.

id  price total_price --------------------------------- 4   100   100.00 5   100   200.00 2   300   500.00 3   400   900.00 

atm i'm using query similar below one:

set @total=0;  select a.id, a.price , @total:=@total + a.price total_price , a.id_user  shares  a.`id_user` != 0 , a.id_object = 1  having @total < 1000.00  order a.price asc; 

it works fine it's not efficient. takes around 1.5 seconds extract data (the table has around 1m lines).

the problem related having clause.

do have suggestions?

is there way perform type of query without using clause having ?

i believe (cumulative sum) looking for:

set @total = 0;  select id,        price,        total_price (     select a.*         ,(@total := @total + price) total_price     shares     a.id_user != 0         , a.id_object = 1     order a.price     ) q1 q1.total_price < 1000; 

sql fiddle demo


Comments

Popular posts from this blog

javascript - How to diff two immutable objects -

c# - How can I have the VS Debugger break in the correct location for exceptions thrown in Async methods in a Console App? -

javascript - React.js: onClick function from child to parent -