Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql select top n rows whilte count x<y

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

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

lets say y=15 so in this case I want top 2 rows 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 this possible?

UPDATE:

I am creating an email queue system where every email sent by my system gets stored in this table.Each email can have multiple recipients and I don't want to break them down to 1 recipient per each email row ( one of the modules whom sends email is newsletter which each mail can have dozens or even hundreds of recipients which I only break them into 50 recipient stacks) so in my emails table I have a column which tells me how many recipients that email have.

SO every row's count column can have a value from 1 to 50 , now I want to send 50 email every few minutes, here is where I need this query to select top 50 email which can be contained in 1 or more(n) rows.

like image 930
Exlord Avatar asked Mar 21 '23 17:03

Exlord


1 Answers

Yes, it is:

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;
like image 77
Alma Do Avatar answered Apr 01 '23 09:04

Alma Do