然后mysql中的sum列使用where子句中的结果

时间:2013-03-25 15:36:07

标签: mysql sql

我希望能够做到这一点:

SELECT dept.id, (invoices.col1 + invoices.col2 + invoices.col3) as sumTotal 
FROM dept 
     INNER JOIN invoices ON invoices.id_dept = dept.id 
WHERE sumTotal > 10000

但是我使用“sumTotal”获得了一个未知的专栏。

这可能吗?

4 个答案:

答案 0 :(得分:16)

使用HAVING

SELECT dept.id, (invoices.col1 + invoices.col2 + invoices.col3) as sumTotal 
FROM dept 
INNER JOIN invoices
    ON invoices.id_dept = dept.id 
HAVING sumTotal > 10000

问题是在WHERE语句之前SELECT子句已执行。因此,sumTotal列尚不可用。

HAVING语句之后SELECT子句执行。在选择所有内容后,它会过滤掉结果。但请记住,因为使用HAVING的速度较慢。它在整行行上运行。

来自MySQL documentation

  

HAVING子句几乎在最后一次应用,就在项目发送到客户端之前,没有优化。 (在HAVING之后应用LIMIT。)

     

SQL标准要求HAVING必须仅引用GROUP BY子句中的列或聚合函数中使用的列。但是,MySQL支持对此行为的扩展,并允许HAVING引用SELECT列表中的列和外部子查询中的列。


  

HAVING子句可以引用聚合函数,WHERE子句不能:

SELECT user, MAX(salary)
FROM users
GROUP BY user
HAVING MAX(salary) > 10;
  

不要将HAVING用于WHERE子句中的项目。

答案 1 :(得分:5)

或使用WHERE ......

SELECT dept.id, (invoices.col1 + invoices.col2 + invoices.col3) as sumTotal 
  FROM dept 
  JOIN invoices ON invoices.id_dept = dept.id 
 WHERE invoices.col1 + invoices.col2 + invoices.col3 > 10000

答案 2 :(得分:4)

你也可以试试这个:

WITH temp AS
(
 SELECT
   dept.id,
   (invoices.col1 + invoices.col2 + invoices.col3) as sumTotal 
 FROM dept INNER JOIN invoices ON invoices.id_dept = dept.id
)
SELECT *
FROM temp
WHERE sumTotal > 10000

答案 3 :(得分:1)

你必须使用'have' -

SELECT dept.id, (invoices.col1 + invoices.col2 + invoices.col3) as sumTotal 
FROM dept 
INNER JOIN invoices ON invoices.id_dept = dept.id 
HAVING sumTotal > 10000

我不确定您是否可以使用别名字段或是否必须写'having(invoices.col1 + invoices.col2 + invoices.col3)> 10000

'where'语句与'select'一起使用:它过滤最初返回的记录。 'have'然后过滤返回的数据集,通常是因为'select'时无法知道'having'条件。

引用一个文档,'HAVING子句已添加到SQL,因为WHERE关键字不能与聚合函数一起使用。'其他地方写成' SQL HAVING子句与SQL GROUP BY子句结合使用。它可以在SQL SELECT语句中用于过滤SQL GROUP BY返回的记录。'