在一个 mysql 查询中获取男性/女性/所有人的平均投票评级

发布于 2024-11-19 08:50:59 字数 829 浏览 2 评论 0原文

我有以下头痛......我试图一次获得三个不同子句的平均评级,我想也许使用 UNION 命令会起作用,但它只会从第一个查询(要求平均评级的查询)中找到值。 averageMaleRating 和averageFemaleRating 作为未知列返回...

这是查询!

SELECT
  averageRating,
  averageMaleRating,
  averageFemaleRating
FROM (
  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  GROUP BY question_id

  UNION

  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageMaleRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  AND
    GENDER = 'male'
  GROUP BY question_id

  UNION

  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageFemaleRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  AND
    GENDER = 'female'
  GROUP BY question_id
 )AS bigU
JOIN
  wp_ratings
ON
  wp_ratings.question_id = bigU.q_id

I have the following headache… I'm trying to get the average rating for three different clauses in one go, I thought maybe using the UNION command would work but it will only find values from the first query (the one asking for averageRating). averageMaleRating and averageFemaleRating are returned as unknown columns…

And here's the query!

SELECT
  averageRating,
  averageMaleRating,
  averageFemaleRating
FROM (
  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  GROUP BY question_id

  UNION

  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageMaleRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  AND
    GENDER = 'male'
  GROUP BY question_id

  UNION

  SELECT
    question_id AS q_id,
    ROUND(AVG(rating)) AS averageFemaleRating
  FROM
    wp_ratings
  WHERE
    club_id = ?
  AND
    GENDER = 'female'
  GROUP BY question_id
 )AS bigU
JOIN
  wp_ratings
ON
  wp_ratings.question_id = bigU.q_id

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

躲猫猫 2024-11-26 08:50:59

您使用 UNION 语句完全错误。

您需要从问题表中选择并加入每个性别的评分表

SELECT
  q.id,
  AVG(t.rating) AS avgTotal,
  AVG(m.rating) AS avgMale,
  AVG(f.rating) AS avgFemale
FROM questions AS q

LEFT JOIN ratings AS t
ON q.id = t.question_id

LEFT JOIN ratings AS m
ON q.id = m.question_id AND m.gender = 'male'

LEFT JOIN ratings AS f
ON q.id = f.question_id AND f.gender = 'female'

GROUP BY q.id

You're using UNION statement totally wrong.

You need to select from Question table and join Ratings table for each gender

SELECT
  q.id,
  AVG(t.rating) AS avgTotal,
  AVG(m.rating) AS avgMale,
  AVG(f.rating) AS avgFemale
FROM questions AS q

LEFT JOIN ratings AS t
ON q.id = t.question_id

LEFT JOIN ratings AS m
ON q.id = m.question_id AND m.gender = 'male'

LEFT JOIN ratings AS f
ON q.id = f.question_id AND f.gender = 'female'

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