1

我有一个 MySQL 数据库,我在其中运行某些存储过程。

在其中一个中,我想总结某个用户必须支付的金额,他已经支付的金额并返回所有用户,其中要支付的金额不等于支付的金额。我想出了以下(简化的)查询:

SELECT userId, SUM(costs) as sum_costs, 
  (SELECT SUM(payed)
   FROM payments p WHERE ta.userId=p.userId) as sum_payed
FROM ta 
GROUP BY ta.userId
ORDER BY ta.userId;

这给了我每个用户的费用和付款的总和。但我不知道,我如何才能只选择成本和付款不相等的用户。

WHERE sum_costs != sum_payed 

不起作用,因为 mysql 不知道 WHERE 子句中的“sum_costs”列。

任何想法,如何让选择工作?

4

3 回答 3

1
SELECT * FROM 
(
SELECT userId, SUM(costs) as sum_costs, 
(SELECT SUM(payed)
FROM payments p WHERE ta.userId=p.userId) as sum_payed
FROM ta 
GROUP BY ta.userId
)a
WHERE a.sum_costs <> a.sum_payed 
--ORDER BY a.userId;

更新:实际上不需要,ORDER BY UserId因为它将由隐式订购GROUP BY

于 2012-12-12T19:24:50.703 回答
1
SELECT * from
(select userId, SUM(costs) as sum_costs
    FROM ta 
       GROUP BY ta.userId) t1
 left join
  (SELECT userId,SUM(payed) as sum_payed FROM payments p group by userId) t2
   on t1.UserId=t2.UserId

where t1.sum_costs<>t2.sum_payed
ORDER BY t1.userId;
于 2012-12-12T19:47:36.597 回答
0
WHERE SUM(costs) <> (SELECT SUM(payed) FROM payments p WHERE ta.userId=p.userId)
于 2012-12-12T19:24:33.527 回答