2011-10-27 102 views
1

例如,我有以下查询来获取上个月提交的浏览次数最多的文章。通过查询优化MySQL订单

explain 
SELECT * 
FROM article 
WHERE date > 1315391769 
ORDER BY views DESC 
LIMIT 10 

如何为此查询选择正确的索引?或者如何重新编写它以避免扫描大量行或文件排序?

这是与当前的指标我想表方案:

CREATE TABLE `article` (
    `id` int(11) NOT NULL auto_increment, 
    `title` varchar(50) NOT NULL, 
    `body` text NOT NULL, 
    `date` int(32) NOT NULL, 
    `views` int(11) NOT NULL default '0', 
    PRIMARY KEY (`id`), 
    KEY `date` (`date`), 
    KEY `views` (`views`), 
    KEY `date_2` (`date`,`views`), 
    KEY `views_2` (`views`,`date`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=200003 ; 

-- 
-- Dumping data for table `article` 
-- 

INSERT INTO `article` VALUES (1, 'title test113', 'test body118', 1317912183, 5017); 
INSERT INTO `article` VALUES (2, 'title test193', 'test body193', 1313441124, 5943); 
INSERT INTO `article` VALUES (3, 'title test112', 'test body116', 1312773586, 653); 
INSERT INTO `article` VALUES (4, 'title test378', 'test body374', 1316786646, 4589); 
INSERT INTO `article` VALUES (5, 'title test335', 'test body3310', 1319173694, 6224); 

注意:我也尝试过MySQL的日期,而不是Unix时间戳,但我得到了同样的结果。

这是解释输出:

id select_type  table type possible_keys key  key_len  ref  rows Extra 
1 SIMPLE article  range date,date_2  date 4 NULL 107245 Using where; Using filesort 
+0

@我贴只有5行作为样本。 –

+0

什么是int(32)?这是否有点签署更大的整数?就此而言,什么是int(11)? http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html –

+0

它应该是11不是32.我已经改变它到MySQL时间和MySQL日期时间,我得到了同样的结果。 –

回答

1

单个键date_2dateviews)应该给用于所讨论的查询最佳性能。见here我不认为其他指标会帮助。由于查询非常简单,我无法想象任何其他优化!

+0

不,user_ksa是正确的。可以使用'(日期)'或'(视图)'索引。 –

1

对于此类查询,只能使用(date)(views)索引,而不能使用索引(date,views)。 MySQL选择使用什么可能是最优的也可能不是最优的。 2月份的最优数据可能不会用于4月份的数据!

  • 您可以尝试强制其中的一种测量性能。

  • 您可以与Year-Month数据添加计算的列,使用CHAR(6)201104为2011年4月(即列可以使用INSERT和UPDATE触发器被更新)或者int24136(24136 = 2011×12 + 4)。

那么你的条件是:

WHERE YearMonth = '201109'   --- for September 

WHERE YearMonth = 2011*12+9  

,并且可以使用(YearMonth, views)指数。

1

通过强制指数实现。

explain 
SELECT * 
FROM article force index (`views`) 
WHERE date>=1315391768 
ORDER BY views DESC 
LIMIT 10 

解释计划:

"id" "select_type" "table"  "type"  "possible_keys" "key" "key_len"  "ref" "rows" "Extra" 
"1" "SIMPLE"  "article" "index"   \N   "views" "4"   \N "5" "Using where"