您好,登錄后才能下訂單哦!
這篇文章主要介紹了MySQL如何使用變量實(shí)現(xiàn)各種排序,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
核心代碼
--下面我演示下MySQL中的排序列的實(shí)現(xiàn) --測試數(shù)據(jù) CREATE TABLE tb ( score INT ); INSERT tb SELECT 5 UNION ALL SELECT 4 UNION ALL SELECT 4 UNION ALL SELECT 4 UNION ALL SELECT 3 UNION ALL SELECT 2 UNION ALL SELECT 1; --1.row_number式的排序 SET @row_number =0; SELECT @row_number := @row_number+1 AS row_number,score FROM tb ORDER BY score DESC ; +------------+-------+ | row_number | score | +------------+-------+ | 1 | 5 | | 2 | 4 | | 3 | 4 | | 4 | 4 | | 5 | 3 | | 6 | 2 | | 7 | 1 | +------------+-------+ --2.dense_rank式的排序 SET @dense_rank = 0,@prev_score = NULL; SELECT @dense_rank :=IF(@prev_score=score,@dense_rank,@dense_rank+1) AS decnse_rank, @prev_score := score AS score FROM tb ORDER BY score DESC ; +-------------+-------+ | decnse_rank | score | +-------------+-------+ | 1 | 5 | | 2 | 4 | | 2 | 4 | | 2 | 4 | | 3 | 3 | | 4 | 2 | | 5 | 1 | +-------------+-------+ --3.rank式的排序 SET @row=0,@rank=0,@prev_score=NULL; SELECT @row:=@row+1 AS ROW, @rank:=IF(@prev_score=score,@rank,@row) AS rank, @prev_score:=score AS score FROM tb ORDER BY score DESC; +------+------+-------+ | ROW | rank | score | +------+------+-------+ | 1 | 1 | 5 | | 2 | 2 | 4 | | 3 | 2 | 4 | | 4 | 2 | 4 | | 5 | 5 | 3 | | 6 | 6 | 2 | | 7 | 7 | 1 | +------+------+-------+
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享MySQL如何使用變量實(shí)現(xiàn)各種排序內(nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。