0

我有一个这样的 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;

我想将结果限制为 Occurrences>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;
4

5 回答 5

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;
于 2009-01-27T01:15:13.697 回答
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
于 2013-01-11T06:59:13.847 回答
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 一起工作正常,

于 2009-01-27T01:19:37.323 回答
0

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

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

于 2009-01-27T01:13:48.020 回答
0

我相信聚合应该在HAVING条款中。不过,诚然,我不确定是否接受别名。

HAVING (Occurrences > 0)

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

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

SELECT *
FROM (
   -- your current query
) AS sub
WHERE (Occurences > 0)
于 2009-01-27T01:15:06.693 回答