1. 程式人生 > >mysql sum()函式怎麼得不到正確的結果啊!!!!

mysql sum()函式怎麼得不到正確的結果啊!!!!

問題是這樣的:一個充值表state=1表示充值成功的,一個消費表state=1表示消費成功的。我要列出充值成功的總值大於消費成功的總值所以使用者id,充值總值,消費總值。語句如下:
SELECT a.userid,SUM(a.number) AS mai,SUM(i.total) AS hua
FROM account AS a,info AS i
WHERE a.state=1 AND a.userid=i.userid AND i.state=1
GROUP BY a.userid
HAVING SUM(a.number)>SUM(i.total)
但是充值總值,消費總值錯誤了。。。
比如充值4次成功。消費3次成功。
列出的充值額是真值*3次。消費額是真值*4次啊!!!!這不是我要的結果啊!!

求正確的語句!!!!!!


SELECT 
  a.userid,
  a.mai,
  i.hua
FROM 
  (SELECT userid, SUM(number) AS mai FROM account WHERE state=1 GROUP BY userid) AS a,
  (SELECT userid, SUM(total) AS hua FROM info  WHERE state=1  GROUP BY userid) AS i
WHERE 
  a.userid=i.userid
  AND a.mai > i.hua