Table
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`created` int(11) NOT NULL,
`updated` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
ALTER TABLE `articles`
ADD PRIMARY KEY (`id`), ADD KEY `category_id` (`category_id`,`created`);
我的测试:
查询1
SELECT sql_no_cache * FROM `articles` WHERE category_id=1 order by created limit 0,15
平均时间: 0.0003
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE articles ref category_id category_id 4 const 1029 Using where
查询2
SELECT sql_no_cache * FROM `articles` WHERE category_id=1 order by updated limit 0,15
平均时间: 0.0019
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE articles ref category_id category_id 4 const 1029 Using where; Using filesort
查询3
SELECT sql_no_cache * FROM `articles` WHERE category_id in (1,2,3) order by created limit 0,15
平均时间: 0.0018
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE articles range category_id category_id 4 NULL 1105 Using where; Using filesort
查询4
SELECT sql_no_cache * FROM `articles` WHERE category_id in (1,2,3) order by updated limit 0,15
平均时间: 0.0018
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE articles range category_id category_id 4 NULL 1105 Using where; Using filesort
我的最终需求是查询3。
但是从测试中,我认为只有 query1 使用索引,因为执行时间比其他时间短得多。
问题:
- 创建时有索引,更新时没有索引,为什么查询 3 和查询 4 节省了执行时间?
- 如何使查询 3 使用索引,或者如何提高查询 3 的性能?
根据这个MySQL文档,如果"查询在索引的非连续部分使用ORDER BY",MySQL不能使用索引进行排序。"in"条款就是这种情况。
如果您的 ID 列是自动递增的整数,并且创建是指记录的创建日期,则可以改为按 ID 排序。这将实现我相信你想做的事情,但这当然是一个黑客......
你是否使用"created"是一个表关键字,你不用作字段名称。但
从 category_id in(1,3,7,12,234,333,456) 按 DESC 限制 0,20 排序的文章中选择标题 created
或从文章中选择 art.title 作为艺术,其中 art.category_id in(1,3,7,12,234,333,456) 按 art.created
DESC 限制 0,20 排序
试试这是工作