Mysql 中因爲沒有ROWNUM僞列、 那麼想要排名、 我們就先要搞出一列僞列、 用作排名
僞列爲分組排名的核心內容
SELECT
(@r :=@r + 1) AS rank
FROM (SELECT @r := 0) r
;
舉個例子:
創建臨時表插入測試數據
CREATE TEMPORARY TABLE tm_test (num int , createdat datetime );
INSERT INTO tm_test (num, createdat) VALUES (1, '2018/12/28 21:41:20');
INSERT INTO tm_test (num, createdat) VALUES (1, '2018/12/28 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (1, '2018/12/28 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (1, '2018/12/28 21:43:20');
INSERT INTO tm_test (num, createdat) VALUES (1, '2018/12/28 21:44:20');
INSERT INTO tm_test (num, createdat) VALUES (2, '2018/12/29 21:41:20');
INSERT INTO tm_test (num, createdat) VALUES (2, '2018/12/29 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (2, '2018/12/29 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (2, '2018/12/29 21:43:20');
INSERT INTO tm_test (num, createdat) VALUES (2, '2018/12/29 21:44:20');
INSERT INTO tm_test (num, createdat) VALUES (3, '2018/12/30 21:41:20');
INSERT INTO tm_test (num, createdat) VALUES (3, '2018/12/30 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (3, '2018/12/30 21:42:20');
INSERT INTO tm_test (num, createdat) VALUES (3, '2018/12/30 21:43:20');
INSERT INTO tm_test (num, createdat) VALUES (3, '2018/12/30 21:44:20');
SELECT * FROM tm_test;
根據某列順序排名:
SELECT a.*,(@r :=@r + 1) AS rank
FROM tm_test a,(SELECT @r := 0) r
ORDER BY createdat;
根據某列順序排名(相同內容排名一致):
SELECT a.* ,
CASE
WHEN @p=a.createdat THEN @r
WHEN @p:=a.createdat THEN @r:=@r+1
END rank
FROM tm_test a ,(SELECT @r:=0,@p:=NULL)r
ORDER BY a.createdat;
分組排名:
SELECT num,createdat,rank
FROM
(
SELECT a.*,IF(@p=a.num,@r:=@r+1,@r:=1) AS rank,
@p:= a.num
FROM tm_test a,(SELECT @p:=NULL,@r:=0)r
ORDER BY a.num,a.createdat
)z;
分組排名(相同內容排名一致):
SELECT num,createdat,rank
FROM
(
SELECT *,
IF(@p=num,
CASE
WHEN @s=createdat THEN @r
WHEN @s:=createdat THEN @r:=@r+1
END,
@r:=1 ) AS rank,
@p:=num,
@s:=createdat
FROM tm_test,(SELECT @p:=NULL,@s:=NULL,@r:=0)r
ORDER BY num,createdat desc
)z;