2012-03-02 74 views
15

我的SQL查询:mysql fix使用where;

SELECT * 
FROM updates_cats 
WHERE uid =118697835834 
ORDER BY created_date ASC 

当前指数:

index1(uid, created_date) 

EXPLAIN EXTENDED结果:

1 SIMPLE updates_cats ref index1 index1 8 const 2 100.00 Using where 

如何解决它已经用在那里,因此它可以使用额外的字段索引呢?

编辑:SHOW CREATE TABLE:

CREATE TABLE `updates_cats` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
`u_cat_id` bigint(20) NOT NULL DEFAULT '0', 
`uid` bigint(20) NOT NULL, 
`u_cat_name` text COLLATE utf8_unicode_ci NOT NULL, 
`total_updates` int(11) unsigned NOT NULL DEFAULT '0', 
`created_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', 
PRIMARY KEY (`id`), 
KEY `index1` (`uid`,`created_date`) 
) ENGINE=MyISAM AUTO_INCREMENT=23522 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 
+0

+1。虽然删除了PHP标记。 – 2012-03-02 13:11:35

+0

@fxuser:表格有多少行?如果他们太少,那么eindex可能不会被起诉。 – 2012-03-02 13:46:22

+0

@ypercube显示第0 - 29行(总共23,521,查询花了0.0005秒) – fxuser 2012-03-02 13:49:07

回答

29

,这将是比Using whereUsing where; Using index一个 “覆盖索引” 的唯一的事情。尝试选择uidcreated_date

Using where很好。这意味着它将指示的索引应用于WHERE子句并减少返回的行。要摆脱它,你必须摆脱WHERE条款。

这里有事情,你应该关注:

  • Using filesort
  • Using temporary
  • 不使用索引:NULLEXPLAIN的“关键”列,并在大量的行'行'列。

EXPLAIN结果表明,MySQL是应用index1WHERE条款并返回2行:为合理的问题

1 SIMPLE updates_cats ref index1 index1 8 const 2 100.00 Using where 
+0

因为我使用SELECT *它意味着我想要大多数(如果不是全部)表的列...所以如果我只选择uid,created_date会有什么帮助? – fxuser 2012-03-02 14:46:18

+0

只用'uid'和'created_date'来尝试。你的'EXPLAIN'会显示'使用索引',这意味着MySQL能够直接从索引返回整个结果集,而不必访问实际的表数据。这可以防止两次搜索,每次返回一行。如果您选择了“text”字段,则无论如何您都不能使用覆盖索引,因此请坚持您所拥有的内容。阅读“[涵盖索引](http://www.mysqlperformanceblog.com/2006/11/23/covering-index-and-prefix-indexes/)”。 – 2012-03-02 14:53:29

+0

刚刚尝试过,但它会返回PHP错误,说一个变量试图得到一个未在SELECT中指定的列... – fxuser 2012-03-02 15:13:24