【发布时间】:2016-03-03 23:20:38
【问题描述】:
表格
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
我的最终需求是query3。
但从测试来看,我认为只有 query1 使用了索引,因为执行时间比其他的要短得多。
问题:
- created 上有索引,updated 上没有索引,为什么 query3 和 query4 节省了执行时间?
- 如何让 query3 使用索引,或者如何提高 Query3 的性能?
【问题讨论】:
-
@Yossi 类别 ID 可以是任何类型。用例是:用户订阅了几个分类,系统根据他订阅的分类展示文章。
-
你能发布解释吗?您假设没有使用索引,但情况可能并非如此。响应时间因许多其他不相关的因素而异...
-
您在 created 、 category_id 上是否有索引,或者两者都有索引(如果有,按什么顺序)?
-
@NevilleK 我测试了 100 次以获得平均执行时间,还添加了“sql_no_cache”。添加了解释。
-
@Kickstart 我更新了问题并添加了完整的表格结构。
标签: mysql