文章目录
前言
`
MySQL5.7版本没有row_number()over()函数,MySQL8以上版本才有,但是MySql5.7安装的版本较多,在5.7如何进行排序分组。
一、准备数据
sql
CREATE TABLE POSTS(POST_ID INT,
USER_ID INT, -- 用户ID
CATEGORY_ID INT,-- 分类ID
POST_TITLE VARCHAR(400),
CREATE_TIME DATE, -- 创建时间
LAST_EDIT_TIME DATE, -- 最后编辑时间
VIEW_COUNT INT,-- 访问量
REPLY_COUNT INT -- 回复量
);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(1,1,1,'标题1',now(),now(),100,400);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(2,1,1,'标题2',now(),now(),200,300);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(3,2,1,'标题3',now(),now(),300,200);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(4,2,1,'标题4',now(),now(),400,100);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(5,2,1,'标题5',now(),now(),500,100);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(6,1,2,'标题4',now(),now(),600,100);
INSERT INTO POSTS(POST_ID,USER_ID,CATEGORY_ID,POST_TITLE,CREATE_TIME,LAST_EDIT_TIME,VIEW_COUNT,REPLY_COUNT)VALUES(7,2,2,'标题5',now(),now(),700,100);
二、查询
根据查询各个分类的访问量的排名
sql
SELECT A.*,@last :=IF(@FIRST = A.CATEGORY_ID, @last + 1, 1 ) AS rn, @FIRST := A.CATEGORY_ID
FROM POSTS A,(SELECT @last := 0, @FIRST := NULL ) B
ORDER BY A.CATEGORY_ID,VIEW_COUNT DESC;