在where子句中使用函数

时间:2012-12-12 19:21:01

标签: mysql sql stored-procedures

我有一个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'。

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

3 个答案:

答案 0 :(得分: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

隐式排序

答案 1 :(得分: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;

答案 2 :(得分:0)

WHERE SUM(costs) <> (SELECT SUM(payed) FROM payments p WHERE ta.userId=p.userId)