我有这样的声明:
SELECT count(s.name), s.name, avg(a.rate), @curRank := @curRank + 1 AS rank
FROM `avatec_objects_comments` as a, avatec_objects as s, (SELECT @curRank := 0) r
WHERE a.oid =s.id and s.status=0
GROUP BY s.name
ORDER BY avg(a.rate) desc, count(s.name) desc
这是我想要的结果(见侧面的数字)
如何根据count(s.name)
和avg(a.rate)
设置上述所需结果中的排名?
答案 0 :(得分:1)
MySQL似乎在使用group by
变量时遇到问题。解决方案是使用子查询。此外,您可以使用显式join
语法来改进查询:
SELECT cnt, name, avgrate,
(@curRank := @curRank + 1) AS rank
FROM (SELECT count(o.name) as cnt, o.name, avg(oc.rate) as avgrate,
FROM avatec_objects o JOIN
avatec_objects_comments oc
ON oc.oid = o.id
WHERE o.status = 0
GROUP BY o.name
) oc CROSS JOIN
(SELECT @curRank := 0) vars
ORDER BY avgrate desc, cnt desc;
答案 1 :(得分:0)
您必须嵌套查询。订购将作为此查询中的最后一个操作完成,因此它将始终替换您的排名。请查看以下内容:
SET @rank=0;
SELECT t1.*, @rank:=@rank+1 AS rank FROM
(SELECT count(s.name), s.name, avg(a.rate)
FROM `avatec_objects_comments` as a, avatec_objects as s
WHERE a.oid =s.id and s.status=0
GROUP BY s.name
ORDER BY avg(a.rate) desc, count(s.name) desc)) t1;
在此查询中,您将获得所需的数据(将被选中,分组并排序十个),然后它只会将数据添加到准备阅读的数据中。