限制两列总和的结果

时间:2013-06-24 17:03:08

标签: php mysql

表:

id | c1  | c2
-------------    
1  | 10 | 20
2  | 55 | 20
3  | 30 | 30
4  | 11 | 80
5  | 12 | 20

和查询

select (sum(c1)+sum(c2))as sum from mytable where sum > 100 ??

以上生成错误,因为sum不是表的一部分。任何限制/限制结果条件的工作只返回两列总和的条件? (不需要在表格中添加第三列)

谢谢

3 个答案:

答案 0 :(得分:4)

我相信您正在寻找HAVING条款。

所以,

SELECT (SUM(c1)+SUM(C2)) AS sum FROM mytable HAVING sum > 100;

答案 1 :(得分:2)

您可以将现有查询包装在另一个选择中:

select total
from
(
  select sum(c1 + c2) as total 
  from mytable 
) d
where total > 100;

或者您可以使用HAVING cluase:

select sum(c1 + c2) as total 
from mytable 
having sum(c1 + c2) > 100;  -- you can also use the total alias in the having

SQL Fiddle with Demo

答案 2 :(得分:1)

这个答案与艾哈迈德的评论有关:

SELECT (c1+c2) AS sum FROM mytable WHERE ID > 5  GROUP BY ID HAVING sum > 100;