MySQL中的排名函数指定排名

时间:2016-12-17 10:43:54

标签: mysql sql rank

我需要为TC5分配一个等级而不是id。

SELECT a.id, a.user_id, a.tc1, a.tc4, min(a.tc5), a.tc2, b.avatar, c.username, @curRank := @curRank + 1 AS Rank
FROM 
treningove_casy a INNER JOIN  
sn_users b ON a.user_id=b.id INNER JOIN
users c ON a.user_id=c.id , (SELECT @curRank := 0) r
WHERE  a.tc2 LIKE  'Motokáry Modrice' 
GROUP BY a.user_id

那是怎么回事。请帮忙

enter image description here

修改后的代码

SELECT x.*, (@curRank := @curRank + 1) as Rank
FROM (SELECT a.id, a.user_id, a.tc1, a.tc4, min(a.tc5) as tc5,
             a.tc2, b.avatar, c.username, 
      FROM sbhgl_chronoengine_chronoforms_datatable_treningove_casy a INNER JOIN  
           sbhgl_jsn_users b
           ON a.user_id = b.id INNER JOIN
           sbhgl_users c
           ON a.user_id = c.id 
      WHERE  a.tc2 LIKE  'Motokáry Modřice' 
      GROUP BY a.user_id
     ) x CROSS JOIN
     (SELECT @curRank := 0) params
ORDER BY tc5 DESC;

2 个答案:

答案 0 :(得分:1)

 var query =
                from c in context.Courses
                where

您可以尝试以上解决方案,希望这会对您有所帮助。

答案 1 :(得分:0)

在MySQL中,您通常使用变量作为排名。在您的情况下,您将使用子查询。我发现变量方法并不总是与GROUP BY一起使用:

SELECT x.*, (@curRank := @curRank + 1) as Rank
FROM (SELECT a.id, a.user_id, a.tc1, a.tc4, min(a.tc5) as tc5,
             a.tc2, b.avatar, c.username, 
      FROM treningove_casy a INNER JOIN  
           sn_users b
           ON a.user_id = b.id INNER JOIN
           users c
           ON a.user_id = c.id 
      WHERE  a.tc2 LIKE  'Motokáry Modrice' 
      GROUP BY a.user_id
     ) x CROSS JOIN
     (SELECT @curRank := 0) params
ORDER BY tc5 DESC;

注意:表别名的使用是好的。但是,如果别名是表名的缩写,则理解查询要容易得多。