Mysql selects the top n rows while x <y

I have a table with a column called itemCount, and I want to select the top n rows, and SUM(itemCount)less y.

+----+-----------+
| id | itemCount |
+----+-----------+
|  1 |         5 |
|  2 |        10 |
|  3 |         1 |
|  4 |        20 |
+----+-----------+

lets say y=15, so in this case I want the top 2 lines where SUM(itemCount)<=15 I need something like this:

SELECT * FROM `tbl_mail_queue` LIMIT 0,(select count(id) from `tbl_mail_queue` m where SUM(m.`count`)<=15)

Is it possible?

UPDATE:

, , , . , 1 ( , , - , , 50 ), , , .

SO 1 50, 50 , , 50 , 1 (n ) .

+4
1

, :

SELECT 
   test.id,
   test.itemCount 
FROM 
   test 
     LEFT JOIN 
       (SELECT 
         id, 
         @sum:=@sum+itemCount AS current_sum 
        FROM 
          test 
          CROSS JOIN(SELECT @sum:=0) AS init) AS sums 
     ON test.id=sums.id 
WHERE sums.current_sum<=15;
+7

All Articles