我有以下头痛...我试图一次性获得三个不同子句的平均评级,我想也许使用UNION命令可以工作,但它只能从第一个查询中找到值(要求的是averageRating)。 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
答案 0 :(得分:2)
您使用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