php - MySQL WHERE 通过 AS 语句

标签 php mysql

我的 table

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

但我无法通过 as 声明。

最佳答案

您无法访问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 中使用完整表达式是一件奇怪的事情,因为它会导致计算两次。

关于php - MySQL WHERE 通过 AS 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544067/

相关文章:

PHP 使用 POST 时删除换行符

javascript - 保留表单值的后退按钮

java - 尽管事先已填充,文本区域和其他输入仍返回 null

mysql - 我应该为用户信息(如出生日期、姓名等)创建 2 个表 : first for usernames and passwords, 和其他表吗?

java - 连接 mysql 时通信链路失败

php - 在mysqli中调用两个存储过程导致 'Commands out of sync'错误

php - 对连续字符串进行分组的算法

php - 如何捕获下拉选择并插入到数据库中?

php - Ajax不调用回调函数

mysql - 如何在 Yii2 中进行批量数据库插入?