简体   繁体   中英

MySQL SUM() with JOIN and LIMIT

The concerned schema and query is on SQL fiddle here http://sqlfiddle.com/#!2/312d3/16

The JOIN query below gets the result that I want.

SELECT p.*, payer.username as payer_username, payee.username as
payee_username FROM (`payments_history` p)  JOIN (SELECT * FROM users)
AS payer ON `payer`.`user_id` = `p`.`payer_id`  JOIN (SELECT * FROM
users) AS payee ON `payee`.`user_id` = `p`.`payee_id`  ORDER BY
`p`.`created_timestamp`;

Doing a sum() on the "p.amount" column for all the rows works fine too.

SELECT SUM(p.amount)  FROM (`payments_history` p)  JOIN (SELECT * FROM
users) AS payer ON `payer`.`user_id` = `p`.`payer_id`  JOIN (SELECT *
FROM users) AS payee ON `payee`.`user_id` = `p`.`payee_id`  ORDER BY
`p`.`created_timestamp`;

But doing a sum() on the same column for the rows on each page (offset,limit) returns an empty result (I would like to have the total of the "amount" column for the rows on each page).

SELECT SUM(p.amount)  FROM (`payments_history` p)  JOIN (SELECT * FROM
users) AS payer ON `payer`.`user_id` = `p`.`payer_id`  JOIN (SELECT *
FROM users) AS payee ON `payee`.`user_id` = `p`.`payee_id`  ORDER BY
`p`.`created_timestamp` limit 0,2;

Also in the sum() query, when the offset starts from anything greater than 0 (try LIMIT 2,2), it returns an empty result.

What am I doing wrong?. Thank you.

Give this a try:

SELECT SUM(l.amount)  FROM (
  SELECT p.amount FROM payments_history p
  INNER JOIN users payer ON payer.user_id=p.payer_id
  INNER JOIN users payee ON payee.user_id=p.payee_id
  ORDER BY p.created_timestamp
  LIMIT 0,10
) l

I'm not sure if you plan to add other fields to the query, or have further conditions in a WHERE clause, but having those joins in there doesn't seem all that useful right now.

Your question is just a little vague. What will be on the page that you want to have sums on? Is it a report for the specific user? If so, then you can just add a WHERE clause to your query to limit the sum to just that user. Something like:

SELECT SUM(p.amount)  
FROM (`payments_history` p)  
JOIN (SELECT * FROM users) AS payer ON `payer`.`user_id` = `p`.`payer_id`  
JOIN (SELECT * FROM users) AS payee ON `payee`.`user_id` = `p`.`payee_id`
WHERE payer.user_id = [the user id] 
ORDER BY `p`.`created_timestamp`;

If that's not what you want, then you may want to clarify the question a little bit. It's unclear.

Question: Are you trying to get the sum of just one row? (your answer in the comments makes it seem that way) If so, that's just the value in the amount. You can't sum a single value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM