views:

54

answers:

3

If SELECT SUM(amount) FROM transactions ORDER BY order LIMIT 0, 50 sums the amount field for the first 50 records in a table, how do a sum all records after the first 50? In other words, I'd like to do something like SELECT SUM(amount) from transactions ORDER BY order LIMIT 50, *, but that doesn't work.

+2  A: 
SELECT  SUM(amount)
FROM    (
        SELECT  amount
        FROM    transactions
        ORDER BY
                order
        LIMIT 50, 1000000000000
        ) q

Note that your original query:

SELECT  SUM(amount)
FROM    transactions
ORDER BY
        order
LIMIT 0, 50

does not do what you probably think it does. It is synonymous to this:

SELECT  a_sum, order
FROM    (
        SELECT  SUM(amount) AS a_sum, order
        FROM    transactions
        ) q
ORDER BY
        order
LIMIT   0, 50

The inner query (which would normally fail in any other engine but works in MySQL due to its GROUP BY extension syntax) returns only 1 records.

ORDER BY and LIMIT are then applied to that one aggregated record, not to the records of transactions.

Quassnoi
What if you have more than 1000000000000 rows?
Pyrolistical
Any reason for the sub-query? Seems redundant.
keithjgrant
@Pyrolistical: then you consider switching to another engine.
Quassnoi
@keithjgrant: how do you do it without a subquery?
Quassnoi
@keithjgrant: note that `ORDER BY` and `LIMIT` are applied after `SELECT`, so `SUM(amount) FROM transactions ORDER BY order LIMIT 0, 50` is not what you probably think it is: it's the same as a simple `SUM(amount) FROM transactions`.
Quassnoi
Oh right! I totally overlooked that bit.
keithjgrant
+2  A: 

The documentation advices to use an incredible large number as second parameter to LIMIT:

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;
Felix Kling
Accepting this one, since it most directly addresses my question, but thanks (and +1) to @Quassnoi for pointing out my problem with the `ORDER BY`, too
keithjgrant
+2  A: 

There is probably a more efficient way, but you could run a count query first, to retrieve total # of rows in your table:

SELECT count(*) FROM transactions

Stuff that into a variable and use that variable as your second argument for LIMIT. You could probably do this as a nested mysql query.

Banjer