SQL 将 COUNT 和 AVG 查询与 SELECT 结合起来
我需要获取特定用户的平均评分和评分总数,然后选择所有单个评分(评分值、评分文本、创建者):
$rating_query = mysql_query("SELECT COUNT(1) as rating_count
,AVG(rating_value), rating_value, rating_text, creator
FROM user_rating WHERE rated_user = $user_id");
此查询将返回 COUNT(1) 结果和 AVG(评分值)每一行,但我只需要这些值一次。
有什么办法可以做到这一点而不需要进行两个单独的查询吗?
I need to get the average rating and the total number of ratings for a particular user and then select all single ratings (rating_value, rating_text, creator) as well:
$rating_query = mysql_query("SELECT COUNT(1) as rating_count
,AVG(rating_value), rating_value, rating_text, creator
FROM user_rating WHERE rated_user = $user_id");
This query would return the COUNT(1) result and the AVG(rating_value) for every row, but I only need those values once.
Is there any way to do this without making 2 separate queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能有一个我不知道的技巧,但我认为在单个查询中不可能做到这一点。如果这对您有意义,您可以尝试使用
GROUP BY
子句,但我猜它可能对您正在使用的列名没有意义。任何关系都需要在任何给定行和列处有一个原子值,即使该值为空。您要求的是每行中的第 1 列和第 2 列(但第一列除外)没有值,而且我认为这是不可能的。There may be a trick I'm not aware of, but I don't think that's possible to do in a single query. You could try using a
GROUP BY
clause if that would make sense for you, but I'm guessing it probably doesn't from the column names you're using. Any relation requires a single atomic value at any given row and column, even if that value is null. What you are requesting is that columns 1 and 2 in every row but the first have no value, and again I don't think this is possible.