获取未知列错误,从子查询结果中获取列

时间:2016-06-27 03:56:08

标签: mysql sql

SELECT AID,DESCRIPTION,
IFNULL((SELECT SUM(DEBIT) FROM `GL_POSTED_TRANSACTION` WHERE AID = account.AID),0) AS PREV_DEBIT,
IFNULL((SELECT SUM(DEBIT) FROM `GL_POSTED_TRANSACTION` WHERE AID = account.AID),0) AS DEBIT 
FROM GL_ACCOUNT account 
WHERE CLASSID = 1 AND SUBCLASSID = 3
ORDER BY DESCRIPTION;

以上查询结果:   Result

但是当我添加 AND DEBIT> 0 我收到一条错误,说明未知栏DEBIT。

我做错了什么?有人可以解释一下。

1 个答案:

答案 0 :(得分:1)

HAVING子句中添加该条件,而不是WHERE,例如;)

SELECT AID,DESCRIPTION,
IFNULL((SELECT SUM(DEBIT) FROM `GL_POSTED_TRANSACTION` WHERE AID = account.AID),0) AS PREV_DEBIT,
IFNULL((SELECT SUM(DEBIT) FROM `GL_POSTED_TRANSACTION` WHERE AID = account.AID),0) AS DEBIT 
FROM GL_ACCOUNT account 
WHERE CLASSID = 1 AND SUBCLASSID = 3
HAVING DEBIT > 0
ORDER BY DESCRIPTION;