我有这个php / sql查询:
$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;");
当我输出时,计数是正确的,它显示某些项目已收到多少票。
我只是想添加一个WHERE count >= 10
子句,但一切都会中断。显然,当有数千件商品时,有些商品会获得一票,而且会有100%。但这不是一个好的指标。我想打印出至少有10票(或count >= 10
)
答案 0 :(得分: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;
答案 1 :(得分:1)
你需要告诉它你想要计算什么
having count(*) > 10
答案 2 :(得分:1)
您无法对聚合函数(where
)的结果使用count()
过滤器。 where
应用于行级,因为DB正在决定是否在结果集中包含该行 - 此时计数结果尚不可用。
您想要的是having
子句,在计算完所有聚合结果后,将结果作为结果发送到客户端之前的最后步骤之一应用。
...
GROUP BY item_id
HAVING count > 10
ORDER BY ...