SQL 将 COUNT 和 AVG 查询与 SELECT 结合起来

发布于 2024-12-04 23:15:43 字数 331 浏览 1 评论 0原文

我需要获取特定用户的平均评分和评分总数,然后选择所有单个评分(评分值、评分文本、创建者):

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本宫微胖 2024-12-11 23:15:43

可能有一个我不知道的技巧,但我认为在单个查询中不可能做到这一点。如果这对您有意义,您可以尝试使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文