添加列并显示总数

时间:2018-06-16 22:31:49

标签: mysql

我确定已经回答但无法找到。我有以下内容:

select id, one_num, two_num, (IFNULL(one_num,0) + IFNULL(two_num, 0)) as total from posts where total > 0;

它给了我一个错误:

ERROR 1054 (42S22): Unknown column 'total' in 'where clause'

我想我必须做某种子查询。但我没有运气就试过了。

1 个答案:

答案 0 :(得分:3)

您不能在where子句中使用自定义别名来使用having或在where子句中重复完整表达式

select id, one_num, two_num, (ifnull(one_num,0) + ifnull(two_num, 0)) as total
from posts 
having total > 0;

select id, one_num, two_num, (ifnull(one_num,0) + ifnull(two_num, 0)) as total
from posts 
where (ifnull(one_num,0) + ifnull(two_num, 0)) > 0;