反转使用行排名的SQL子查询的顺序

时间:2013-06-04 16:12:37

标签: mysql sql sql-order-by subquery

我有一个MySQL表,其中包含有关程序功能使用情况的统计信息。我从中检索的内容基本上就是这样(这里总共排在前15位):

SELECT function_id, data_timer, SUM( data_counter ) total 
FROM data
GROUP BY function_id 
ORDER BY total DESC

+-------------+------------+-------+
| function_id | data_timer | total |
+-------------+------------+-------+
|          56 |        567 |  4389 |
|          23 |       7880 |  1267 |
|           7 |        145 |   812 |
|         ... |        ... |   ... |
+-------------+------------+-------+

由于这些结果用于网站模块,用户可以选择哪个列用于ORDER BY以及ASC和DESC之间,我需要检索每行的等级。结果。

question的帮助下,我能够为结果的每一行分配一个等级:

SET @rank = 0;
SELECT @rank:=@rank+1 AS rank, function_id, data_timer, SUM( data_counter ) total
FROM data 
WHERE client_id = 2 
GROUP BY function_id 
ORDER BY total DESC

+------+-------------+------------+-------+
| rank | function_id | data_timer | total |
+------+-------------+------------+-------+
|    1 |          56 |        567 |  4389 |
|    2 |          23 |       7880 |  1267 |
|    3 |           7 |        145 |   812 |
|  ... |         ... |        ... |   ... |
+------+-------------+------------+-------+

我现在在尝试反转此表时遇到一些困难,这意味着我希望首先使用最少使用的函数对结果进行排序。这样的事情(假设有76个函数):

+------+-------------+------------+-------+
| rank | function_id | data_timer | total |
+------+-------------+------------+-------+
|   76 |          44 |        346 |     1 |
|   75 |           2 |       3980 |     4 |
|   74 |          13 |        612 |     7 |
|  ... |         ... |        ... |   ... |
+------+-------------+------------+-------+

这是我的SQL查询尝试:

SELECT rank, function_id, data_timer, total
FROM
(
SET @rank = 0;
SELECT @rank:=@rank+1 AS rank, function_id, data_timer, SUM( data_counter ) total
FROM data 
WHERE client_id = 2 
GROUP BY function_id 
ORDER BY total DESC
)
ORDER BY rank DESC

这让我不停地说:

#1064 - You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use near 
'SET @rank = 0' at line 4

由于我不熟悉SQL,我想我错过了一些明显的东西。

任何帮助都将很高兴,谢谢!

2 个答案:

答案 0 :(得分:2)

您正尝试在子查询中分配变量。这不行。将分配移到子查询之外,它应该运行。

SET @rank = 0;
SELECT rank, function_id, data_timer, total
FROM
(
SELECT @rank:=@rank+1 AS rank, function_id, data_timer, SUM( data_counter ) total
FROM data 
WHERE client_id = 2 
GROUP BY function_id 
ORDER BY total DESC
)
ORDER BY rank DESC

答案 1 :(得分:1)

另一种选择是在查询中初始化@rank变量而不是单独的语句:

SELECT rank, function_id, data_timer, total
FROM
(
    SELECT @rank:=@rank+1 AS rank, function_id, data_timer, SUM( data_counter ) total
    FROM data, 
        (SELECT @rank := 0 ) r
    WHERE client_id = 2 
    GROUP BY function_id 
    ORDER BY total DESC
) r
ORDER BY rank DESC