Mysql 在SQL中查找AVG列
我有一个php/sql查询:Mysql 在SQL中查找AVG列,mysql,sql,Mysql,Sql,我有一个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
$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
)您应该使用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;
您应该使用
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;
你需要告诉它你想数什么
having count(*) > 10
你需要告诉它你想数什么
having count(*) > 10
不能对聚合函数(
count()
)的结果使用where
过滤器<代码>其中在行级别应用,因为DB正在决定是否将行包括在结果集中-此时,计数结果还不可用
您需要的是一个having
子句,它是在计算所有聚合结果之后,将结果发送到客户端之前的最后一个步骤之一
...
GROUP BY item_id
HAVING count > 10
ORDER BY ...
不能对聚合函数(
count()
)的结果使用where
过滤器<代码>其中在行级别应用,因为DB正在决定是否将行包括在结果集中-此时,计数结果还不可用
您需要的是一个having
子句,它是在计算所有聚合结果之后,将结果发送到客户端之前的最后一个步骤之一
...
GROUP BY item_id
HAVING count > 10
ORDER BY ...
@tombom:mysql允许在where/having中使用别名。回滚编辑。@tombom:mysql允许在where/having中使用别名。正在回滚编辑。