4

虽然我可以对别名子查询进行分组和排序,但我不能在 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
4

2 回答 2

3

您可以使用 HAVING 子句而不是 WHERE 来执行此操作

句法

于 2009-07-30T21:06:48.003 回答
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
于 2009-07-30T21:10:44.627 回答