如何在MySQL WHERE子句中使用别名列?

时间:2009-01-27 01:08:37

标签: sql mysql where having

我有一个像这样的MySQL查询:

SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;

我想将结果限制为出现次数> 0的行。这对我来说似乎很简单,但我似乎无法使其发挥作用。无论我尝试什么,WHERE或HAVING,每当我尝试添加这个限制时,我得到NO ROWS作为回报。我很肯定我的表中有数据应该返回。有谁知道如何完成我正在做的事情?


我试过这个,但它仍然不起作用。任何想法为什么它仍然不起作用?

SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" HAVING SUM(...some SQL removed for brevety)>0 GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;

5 个答案:

答案 0 :(得分:5)

我对MySQL的熟悉程度与SQL Server不同,但在T-SQL中,你不能在GROUP BY子句中使用别名(我最初也认为是ORDER BY子句,但是后来证明了不正确)。在这种情况下,您希望根据GROUP BY的结果进行过滤,因此我将使用HAVING子句,如下所示:

SELECT *, SUM(... some SQL removed for brevity ...) AS Occurrences
FROM
    some_table AS q
WHERE
    criterion = 'value'
GROUP BY
    q.P_id
HAVING
    SUM(... some SQL removed for brevity ...) > 0
ORDER BY
    Occurrences DESC
LIMIT 10;

答案 1 :(得分:2)

此查询适用于我......

select order_id, sum(qty_ordered) as total_qty 
from sales_flat_order_item 
group by order_id 
having total_qty > 10
order by total_qty desc

答案 2 :(得分:1)

啊,我找到了适合它的地方。

声明现在是:

SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q
WHERE criterion="value" GROUP BY q.P_id HAVING SUM(...some SQL removed for brevety)>0 ORDER BY Occurrences DESC LIMIT 10;

ORDER BY Occurrences似乎工作得很好,

答案 3 :(得分:0)

根据SQL标准,列别名在查询正文中不可用,这是一个混乱的麻烦。鉴于您的尝试,听起来好像MySQL(和其他一些DBMS)也是如此。您可能必须在ORDER BY子句中重复该表达式。

此外,GROUP BY子句应列出*中的每一列,而不仅仅是主键(但从逻辑上讲,指定主键应该足够)。

答案 4 :(得分:0)

我认为聚合应该在HAVING子句中。但诚然,我不确定是否接受了别名。

HAVING (Occurrences > 0)

HAVING (SUM(...some SQL removed for brevety) > 0)

或者,您可以使用子查询:

SELECT *
FROM (
   -- your current query
) AS sub
WHERE (Occurences > 0)