MySQL 實現排名的幾個方法

2021-09-27 09:43:13 字數 807 閱讀 9606

實現排名:

方法一:

select t.*, @sort:= @sort+ 1 as sort from (select @sort:= 0) s, (select * from table_name order by field desc) as t;

方法二:

select t.*, @sort:= @sort+ 1 as sort from (select @sort := 0) s, table_name as t order by t.field desc;

檢視指定使用者排名:

方法一:

select a.* from (select t.*, @sort:= @sort + 1 as sort from (select @sort:= 0) s,(select * from table_name order by field desc) as t) as a where a.id = 1;

方法二:

select a.* from (select t.*, @sort := @sort + 1 as sort from (select @sort := 0) s, table_name as t order by t.field desc) as a where a.id = 1;

備註:① @sort := @sort + 1 其中 :=  是賦值的作用,意思是先執行@sort + 1,然後把值賦給@sort

② (select @sort := 0) r 意思是設定sort欄位的初始值為0,即編號從1開始

③ table_name 指的是你自己的表名

④ field 表的排序字段

mysql排名的實現

首先我們先建立 create table user info id bigint 20 not null auto increment comment 自增id nick name varchar 255 default null comment 暱稱 create date datetime de...

mysql實現排名

心血來潮刷了一波leetcode,遇見個有意思的sql題目。題目連線 編寫乙個 sql 查詢來實現分數排名。如果兩個分數相同,則兩個分數排名 rank 相同。請注意,平分後的下乙個名次應該是下乙個連續的整數值。換句話說,名次之間不應該有 間隔 id score 1 3.50 2 3.65 3 4.0...

mysql 排名 MySQL用變數實現排名

mysql 8.0版本用視窗函式就可以實現排名,有三種方式,對相同值的處理不同 以上區別會在文末舉例,本文主要討論用變數實現排名 5.5版本用不了視窗函式 至少排序視窗用不了,其他的沒試過 那麼對於要顯示排名的需求就得想其他辦法啦,看網上的資料可以用變數來實現,來看看 首先建表並插入資料 資料資料來...