我有一个SQL查询,它可以检索与广告表相关联的评级表的平均评分。
我的查询工作正常,但我想添加一个WHERE语句,只获得获得两个或更多评分的广告。
这是我的疑问:
SELECT ad_id, AVG(rating) as average_rating,
COUNT(user_id) as num_rates
FROM ads_rating
GROUP BY ad_id
我想要的查询:
SELECT ad_id, AVG(rating) as average_rating,
COUNT(user_id) as num_rates
FROM ads_rating
WHERE num_rates > 1
GROUP BY ad_id
但MariaDB告诉我:
[错] 1054 - 未知栏' num_rates'在' where子句'
谢谢,对不起我在MySQL的菜鸟
答案 0 :(得分:3)
您不能在WHERE中使用列别名 所以你需要这样做。
scoreJ1
或者更好地使用HAVING与GROUP BY一起使用
SELECT ad_id, AVG(rating) as average_rating,
COUNT(user_id) as num_rates
FROM ads_rating
WHERE COUNT(user_id) > 1
GROUP BY ad_id