有关的架构和查询在这里是SQL小提琴http://sqlfiddle.com/#!2/312d3/16
下面的JOIN查询获得我想要的结果。
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`;
对" p.amount"进行求和()所有行的列也可以正常工作。
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`;
但是对每个页面上的行(offset,limit)在同一列上执行sum()会返回一个空结果(我希望得到行的" amount"列的总和在每页上。)
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;
同样在sum()查询中,当偏移量从大于0的任何值开始时(尝试LIMIT 2,2),它返回一个空结果。
我做错了什么? 谢谢。
答案 0 :(得分:2)
尝试一下:
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
我不确定你是否计划在查询中添加其他字段,或者在WHERE子句中有其他条件,但是在那里加入这些连接并不是现在看起来都很有用。
答案 1 :(得分:0)
你的问题有点模糊。页面上您想要总结的内容是什么?它是针对特定用户的报告吗?如果是这样,那么您只需在查询中添加WHERE子句即可将总和限制为该用户。类似的东西:
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`;
如果那不是您想要的,那么您可能想稍微澄清一下这个问题。目前还不清楚。
<强>问题:强> 你想要得到一排的总和吗? (你在评论中的回答看起来就像这样)如果是这样的话,那只是金额的价值。您无法对单个值求和。