我有一个多表查询,类似于此(简化版)
SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating
FROM table1
LEFT JOIN table2
ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0 AND rev_status = 1
GROUP BY dom_url
ORDER BY sum_rev_rating/rev_count DESC
问题出在ORDER BY
子句中。这会导致显示MySQL错误,如下所示:
不支持参考'sum_ rev_ rating'(参考组功能)
答案 0 :(得分:14)
您无法使用别名进行计算。这样做的一种方法是简单地创建另一个别名并按顺序排序。
SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating, sum(table2.rev_rating)/count(table2.rev_id) as avg_rev_rating
FROM table1
LEFT JOIN table2
ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0 AND rev_status = 1
GROUP BY dom_url
ORDER BY avg_rev_rating DESC
答案 1 :(得分:1)
我的mysql生锈了;你可以尝试
SELECT columns, count(table2.rev_id) As rev_count,
sum(table2.rev_rating) As sum_rev_rating,
sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
FROM table1
LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0
AND rev_status = 1
GROUP BY dom_url
ORDER BY rev_Ratio DESC
或
SELECT * from (
SELECT columns, count(table2.rev_id) As rev_count,
sum(table2.rev_rating) As sum_rev_rating
FROM table1
LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0
AND rev_status = 1
GROUP BY dom_url
) X
ORDER BY X.sum_rev_rating/X.rev_count DESC
或
SELECT * from (
SELECT columns, count(table2.rev_id) As rev_count,
sum(table2.rev_rating) As sum_rev_rating,
sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
FROM table1
LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0
AND rev_status = 1
GROUP BY dom_url
) X
ORDER BY rev_Ratio DESC