I don’t know how to put the problem’s title, so just forget about the thread’s title. Now let’s say I have this table, let’s say its name is “tbl_cost”…
==========
id|name|cost
==========
1 |a | 2
2 |b | 3
3 |c | 5
4 |d | 3
5 |e | 1
6 |f | 3
I want to show list from tbl_cost that its cost’s sum is less or equal 10,
then I will got
1 | a |2
2 | b |3
3 | c |5
because 2+3+5=10
Currently, I solve this problem by looping the query till found the sum
$i = 0
Looping
SELECT sum(cost) FROM tbl_cost WHERE id <=$i
$i++;
until found the sum
If you know the minimal cost “min_cost”, then you’ll need to retrieve “10/min_cost” first rows from the table ordered by “cost” and do a simple loop in your program (but without querying database 100 times).
Also you solution is incorrect. Assume we have the following table:
(1, a, 12)
(2, b, 10)
(3, c, 4) and so on.
"SELECT sum(cost) FROM tbl_cost WHERE id <=$i" will never find a solution since 12+any cost > 10.