简体   繁体   English

表中的 SQL/PHP 排名(行号)

[英]SQL/PHP Rank (row number) from table

I have a table of horses and I on the horses profile pages i want to show the global rank of the horse, my table look like this.我有一个马匹表,我想在马匹个人资料页面上显示马匹的全球排名,我的表看起来像这样。

id  name       first second third 
282 NewBreed       3      1     0 
278 CueCard        1      1     0 
283 TapTapBoom     1      0     0 
286 Boomboom       0      0     0 
285 Hoe            0      0     0 
284 Boombastic     0      0     0 
287 Haha           0      0     0 
288 Boom           0      0     0 
280 Annie          0      1     0 
279 Boutan         0      1     0 
281 Wahay          0      1     0 
289 42r3etgf       0      0     0 

For instance if I was on the profile for the horse "TapTapBoom" his global rank would be 3rd... How do I get this number?例如,如果我在马“TapTapBoom”的个人资料中,他的全球排名将是第三……我如何获得这个数字? i'm guessing I need to get the row number after I have sorted the table by "First".我猜我需要在按“第一”对表格进行排序后获取行号。

SELECT *
FROM horses
ORDER BY first
DESC
SELECT row_number
WHERE name = TapTapBoom

So in My PHP I need to input the horse ID or name and as a result I get the horses global rank... the rank is his position of the horse in the table after the table has been sorted by "First" in desc order.因此,在我的 PHP 中,我需要输入马的 ID 或名称,结果我得到了马的全球排名……排名是他在表格中按“第一”排序后的马在表格中的位置.

Here is the original table:这是原始表:

在此处输入图片说明

As MySQL does not have a built in row number function like other RDBMS, you will have to use a variable to achieve this:由于 MySQL 没有像其他 RDBMS 那样内置的行号函数,因此您必须使用变量来实现这一点:

SELECT @rank:=@rank+1 AS rank, name, runs
FROM horses, (SELECT @rank=0) vars 
ORDER BY runs DESC, name

This will order by runs in descending order, and in the case of a tie, it will sort the rider names alphabetically in ascending order.这将责令runs降序排列,并在平局的情况下,将骑手名称的字母顺序进行升序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM