虽然我可以对别名子查询进行分组和排序,但我不能在where子句中使用别名。我需要使用连接吗?
使用:
SELECT entries.*,
(SELECT avg(value)
FROM `ratings`
WHERE ratings.entry_id = entries.id) as avg_rating
FROM `entries`
ORDER BY avg_rating DESC
失败(“where子句中的未知列'avg_rating'):
SELECT entries.*,
(SELECT avg(value)
FROM `ratings`
WHERE ratings.entry_id = entries.id) as avg_rating
FROM `entries`
WHERE avg_rating < '4.5000' ORDER BY avg_rating DESC
答案 0 :(得分:3)
我会做一个join和groupby例如,
SELECT entries.*, AVG(value)
FROM entries INNER JOIN ratings ON entries.id = ratings.entry_id
GROUP BY entries.*
HAVING AVG(value) < '4.5000'
ORDER BY AVG(value)
只是伪造的代码,我还建议您将条目列限制为您所需的。
您可以使用别名,例如:
SELECT entries.*, AVG(value) as avg_value
FROM entries INNER JOIN ratings ON entries.id = ratings.entry_id
GROUP BY entries.*
HAVING avg_value < '4.5000'
ORDER BY avg_value
答案 1 :(得分:2)
您可以使用HAVING子句而不是WHERE
来执行此操作