PHP+mysql 实现排名并查询指定排名
需求:
对社区表里的所有参与话题的帖子 根据应援榜的数量 【support_num】实现排名 并得到某一个帖子的具体排名
设计表:
CREATE TABLE `community` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`estate` tinyint(1) NOT NULL DEFAULT '1' COMMENT '删除状态 (1未删除 0删除)',
`isuse` tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否显示 (1显示 0隐藏)',
`objtype` tinyint(1) NOT NULL DEFAULT '1' COMMENT '发帖类型 1个人 2团队',
`userid` int(11) NOT NULL DEFAULT '0' COMMENT '用户编号',
`content` text COMMENT '内容',
`images` varchar(100) NOT NULL DEFAULT '' COMMENT '图片id 以数组的方式存储 最多9张图片',
`videos` varchar(100) DEFAULT '' COMMENT '视频id ',
`type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '类型 0为图片 1为视频',
`praisecount` bigint(20) NOT NULL DEFAULT '0' COMMENT '点赞数量',
`commentcount` bigint(20) NOT NULL DEFAULT '0' COMMENT '评论数量',
`createtime` int(11) NOT NULL DEFAULT '0' COMMENT '发布时间',
`views` int(11) NOT NULL DEFAULT '0' COMMENT '浏览量',
`team_id` int(11) NOT NULL DEFAULT '0' COMMENT '团队id',
`topicid` varchar(20) NOT NULL DEFAULT '0' COMMENT '话题id',
`support_num` int(11) NOT NULL DEFAULT '0' COMMENT '应援棒数量',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2172 DEFAULT CHARSET=utf8mb4 COMMENT='community(社区)';
1、对所有帖子进行排名(带分页)
SELECT
b.id,
b.userid,
b.rownum,
b.createtime,
b.support_num,
b.videos
FROM
(
SELECT
t.*,
@rownum := @rownum + 1 AS rownum
FROM
( SELECT @rownum := 0 ) r,(
SELECT
id,
videos,
support_num,
userid,
createtime
FROM
community
WHERE
estate = 1
AND isuse = 1
AND objtype = 1
AND type = 2
AND topicid = 179
ORDER BY
`support_num` DESC
) AS t
) AS b
LIMIT 0,10
查询结果:
注释:
1、SELECT @rownum := 0:表示对rownum赋初始值0
2、@rownum := @rownum + 1:表示对rownum加1,语句中会从1开始,每一行往下都自动加1
上述代码会根据community表中的support_num从大到小进行排序。
2、得到某个特定帖子的排名
原理:把上步得到的数据看做一张表,根据userid 来查询特定用户的帖子 同一用户多个帖子排名从大到小
SELECT
b.id,
b.userid,
b.rownum,
b.createtime,
b.support_num,
b.videos
FROM
(
SELECT
t.*,
@rownum := @rownum + 1 AS rownum
FROM
( SELECT @rownum := 0 ) r,(
SELECT
id,
videos,
support_num,
userid,
createtime
FROM
community
WHERE
estate = 1
AND isuse = 1
AND objtype = 1
AND type = 2
AND topicid = 179
ORDER BY
`support_num` DESC
) AS t
) AS b
WHERE
userid = $userId
查询结果:
其中 rownum 即对应该帖子的排名