I need a sql query to select rows from my messages queue, until SUM(users_count) reaches at most 1000. BUT there is no problem if there be only one row returned and that row's users_count is greater than 1000.
I need something like: (i added my own keywords)
SELECT * FROM `messages_queue` UNTIL SUM(users_count) < 1000 AT LEAST 1 ROW
This is my table structure:
messages_queue
- msg_id
- msg_body
- users_count (number of message recieptors)
- time (insert time)
I tried to add this as a comment to Mike's answer, however, it is problematic with the @ signs for variables.
To draw on Mike's answer, the query could actually be made shorter by initializing the variable in the FROM clause, e.g.:
This solution will perform a cumulative sum, stopping when the sum exceeds 1000:
That means that if you have two values of, say, 800, the sum total will be 1600. The first SELECT is just to initialise the
@total
variable.If you want to prevent the sum from exceeding 1000, apart from in cases where a single row has a value of greater than 1000, then I think this works, although you'll need to subject it to some rigorous testing:
I think you are looking to do something like this:
I don't think you could to this with a simple MySQL Query.
You will have to use a stored procedure or filter that in your application.
EDIT
I'm no MySQL Guru (could only code stored procedures on oracle and postgres) but you could start here: http://www.mysqltutorial.org/sql-cursor-in-stored-procedures.aspx .
More general informations about the syntax is located here: http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Kudos to Aducci for the pure SQL solution, but as Thomas Berger said, this could end up being a very expensive query. Depending on the size of your table a stored procedure could well be the better approach: