1

I have this php/sql Query:

$result = mysql_query("
            SELECT r.item_id, AVG(rating) AS avgrating, count(rating) AS count, i.item, c.category
            FROM ratings AS r
            LEFT JOIN items AS i
            ON r.item_id = i.items_id
            INNER JOIN master_cat c
            ON c.cat_id = i.cat_id
            GROUP BY item_id 
            ORDER BY avgrating DESC 
            LIMIT 25;");

When I output this, count is correct, it shows how much votes certain items have received.

I simply want to add a WHERE count >= 10 clause but everything breaks. Obviously, when there are thousands of items, some will get one vote and have 100%. But that is not a good indicator. I want to print out items that have at least 10 votes (or count >= 10)

4

3 回答 3

2

你应该having改用where

SELECT 
    r.item_id, AVG(rating) AS avgrating, 
    count(rating) AS count, i.item, c.category
FROM 
    ratings AS r
    LEFT JOIN items AS i
        ON r.item_id = i.items_id
    INNER JOIN master_cat c
        ON c.cat_id = i.cat_id
GROUP BY 
    item_id 
HAVING
    count >= 10
ORDER BY 
    avgrating DESC 
LIMIT 25;
于 2012-09-03T16:31:24.547 回答
1

你需要告诉它你想计算什么

having count(*) > 10
于 2012-09-03T16:32:15.663 回答
1

您不能where对聚合函数 ( count()) 的结果使用过滤器。where在行级别应用,因为数据库正在决定是否在结果集中包含该行 - 此时计数结果尚不可用。

您需要的是一个having子句,在计算完所有聚合结果之后,将其作为结果发送到客户端之前的最后步骤之一应用。

...
GROUP BY item_id
HAVING count > 10
ORDER BY ...
于 2012-09-03T16:33:04.017 回答