MySQL语句由AS语句提供

时间:2013-12-12 12:49:34

标签: php mysql

我的桌子

Table1 :
___________________________________
| ID | UserID | Amount | Date     |
___________________________________
| 1  | 1      | 10     | 2014-12-10
| 2  | 1      | 5      | 2014-12-12
| 3  | 2      | 50     | 2014-12-12

Table2 :
_________________________________________________
| ID | UserID | Amount | Description  | Date     |
_________________________________________________
| 1  | 2      | 50     | Test Payment | 2014-12-10

我希望用户计算余额。我使用这个MySQL代码

SELECT
Distinct(UserID) As User,
(SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) AS Credit,
(SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User) AS Received,
((SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) - (SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User) As Balance
FROM Table1 WHERE Balance>0

但我不能在那里作为陈述。

2 个答案:

答案 0 :(得分:2)

您无法访问aliases in WHERE。您应该在那里填写完整的表达式或使用HAVING

SELECT
Distinct(UserID) As User,
(SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) AS Credit,
(SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User) AS Received,
((SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) - (SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User) As Balance
FROM Table1 
HAVING Balance>0

- 在WHERE中使用完整表达式在大多数情况下都是一个奇怪的事情,因为它会导致计算两次。

答案 1 :(得分:0)

SELECT tabel.*
FROM (
SELECT
Distinct(UserID) As User,
(SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) AS Credit,
(SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User) AS Received,
((SELECT COALESCE(SUM(Amount),0) FROM Table1 WHERE UserID=User) - (SELECT COALESCE(SUM(Amount),0) FROM Table2 WHERE UserID=User)) as Balance
FROM Table1
)  as tabel
WHERE BALANCE > 0