如何创建具有连接和多个排序条件的MySQL5.6排名

68bkxrlz  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(325)

我一直在尝试返回sql查询的秩。

SELECT c.id, c.score, i.sheetscore, @curRank := @curRank + 1 AS rank
FROM chart c LEFT JOIN indicator as i
ON c.indicator_id = i.id, (
SELECT @curRank :=0
) q
ORDER BY c.score DESC, i.sheetscore DESC
;

最后一行应显示正确显示的排序等级。我应该看到rank=1,2,3,但是我得到了这个。。。我已经尝试了许多sql语句的变体,但我无法找到解决方案。

'ID','SCORE','SHEETSCORE', 'RANK'
'11767', '1', '0.7325', '11767'
'11765', '1', '0.7325', '11765'
'8365', '1', '0.6925', '8365'
'8363', '1', '0.6925', '8363'
'8615', '1', '0.6875', '8615'
'8617', '1', '0.6875', '8617'
'11646', '1', '0.685455', '11646'
'11647', '1', '0.685455', '11647'

理想情况下,我会使用此查询:

SELECT RANK from Chart where ID= 11646  ## as an example
l2osamch

l2osamch1#

我建议首先在子查询中加入并排序,然后计算排名。此外,不应混合使用隐式连接和显式连接-事实上,始终使用显式连接:

SELECT x.*, @curRank := @curRank + 1 AS rank
FROM (
    SELECT c.id, c.score, i.sheetscore
    FROM chart c 
    LEFT JOIN indicator i ON c.indicator_id = i.id
    ORDER BY c.score DESC, i.sheetscore DESC
) x
CROSS JOIN (SELECT @curRank :=0) q
ORDER BY score DESC, sheetscore DESC

请注意,如果您运行的是mysql 8.0,那么这是直接使用 row_number() :

SELECT 
    c.id, 
    c.score, 
    i.sheetscore, 
    ROW_NUMBER() OVER(ORDER BY c.score DESC, i.sheetscore DESC) rn
FROM chart c 
LEFT JOIN indicator i ON c.indicator_id = i.id
ORDER BY c.score DESC, i.sheetscore DESC
4nkexdtk

4nkexdtk2#

另一种选择:
确定一个或两个项目的一种非常低效的方法,但对于那些使用pandas和python并且有许多类似查询的人来说,一个很好的解决方案是将sql查询下载到dataframe,然后使用pandas的rank和query工具-分两步进行:
第1步-从上面运行@gmb的答案:

conn = pymysql.connect(host='localhost',
                       database='db',
                       user='user',
                       password='pass')
cur = conn.cursor()    
rank_scores = """SELECT x.*, @curRank := @curRank + 1 AS rank
                            FROM (
                                SELECT c.id, c.score, i.sheetscore
                                FROM chart c 
                                LEFT JOIN indicator i ON c.indicator_id = i.id
                                ORDER BY c.score DESC, i.sheetscore DESC
                            ) x
                            CROSS JOIN (SELECT @curRank :=0) q
                            ORDER BY score DESC, sheetscore DESC ;"""
 df_scorerank = pd.read_sql(rank_scores, conn)
 conn.close()
 cur.close()

步骤2-从Dataframe中提取所需的列组:

chart_rank = df_scorerank.loc[df_scorerank['id'] == chart_id, 'rank'].item()

如上所述,Dataframe现在包含:

'ID','SCORE','SHEETSCORE', 'RANK'
'11767', '1', '0.7325', '1'
'11765', '1', '0.7325', '2'
'8365', '1', '0.6925', '3'
'8363', '1', '0.6925', '4'
'8615', '1', '0.6875', '5'
'8617', '1', '0.6875', '6'
'11646', '1', '0.685455', '7'
'11647', '1', '0.685455', '8'

相关问题