ESR原则
精确(equal)匹配的字段放在最前面,排序(sort)条件放中间,范围(range)匹配的字段放在最后面
原表
CREATE TABLE `CArticleReplyFast77` (
`id` bigint(20) NOT NULL DEFAULT '0' COMMENT '回复id',
`carticle_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '文章id',
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '评论人的user_id',
`reply_type` tinyint(3) NOT NULL DEFAULT '0' COMMENT '回复类型, 0:回复文章 1:回复回复',
`r_status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '回复状态, 1:正常状态 5:审核中 99:已删除',
`r_sort` int(10) unsigned NOT NULL DEFAULT '1' COMMENT '排序字段',
`top_reply_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '顶层父回复id, 回复文章该值为0',
`parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '父回复id, 回复文章该值为0',
`all_child_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '所有层级子回复数',
`child_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '子回复数',
`extra` varchar(1000) NOT NULL DEFAULT '' COMMENT 'json格式字段',
`create_ts` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`update_ts` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_article_id_update_ts` (`carticle_id`,`update_ts`),
KEY `idx_top_reply_id_update_ts` (`top_reply_id`,`update_ts`),
KEY `idx_parent_id` (`parent_id`),
KEY `idx_article_id_sort` (`carticle_id`,`r_sort`),
KEY `idx_article_id_type_status` (`carticle_id`,`reply_type`,`r_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='分表 按carticle_id分表 ';
需要增加按 create_ts 降序
explain select id from CArticleReplyFast77 where carticle_id = 3877 and reply_type=0 and r_status in (1,5) order by create_ts desc limit 0, 20 \G;
按ESR
alter table CArticleReplyFast77 add index idx_article_id_type_cts_status(
carticle_id
,reply_type
,create_ts
,r_status
);
image.png
网友评论