我也不知道的MySQL

March 13th, 2009 | by 超群.com | 知识共享署名-非商业性使用-相同方式共享,转载请保留链接。

以前看过很多文章说MySQL一次查询只能用到一个索引,在实践中也没注意,一直奉为金科玉律,以此教育自己不要乱建索引,殊不知已是明日黄花

MySQL5.0以后引入了index_merge,在一些特定的查询中可以合并索引,详细的内容查看[中文] [英文],接着测试一下,还是那张表,数据还是10,000条。

mysql> desc tbl_name;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| uid   | int(11)      | NO   | MUL | NULL    |       |
| sid   | mediumint(9) | NO   |     | NULL    |       |
| times | mediumint(9) | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

执行查询测试:

mysql> explain select * from tbl_name where uid = 104460 and times = 38\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tbl_name
         type: ref
possible_keys: uid
          key: uid
      key_len: 4
          ref: const
         rows: 9
        Extra: Using where
1 row in set (0.00 sec)

用到了uid索引,扫描了9行。在times上也加上索引:

mysql> create index times on tbl_name(times);

再执行上面的查询:

mysql> explain select * from tbl_name where uid = 104460 and times = 38\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tbl_name
         type: index_merge
possible_keys: uid,times
          key: uid,times
      key_len: 4,3
          ref: NULL
         rows: 1
        Extra: Using intersect(uid,times); Using where
1 row in set (0.00 sec)

用到了索引合并交集访问算法,只扫描了一行。注意索引合并只对一些特定的查询有用(注意看文档),比如下面的:

mysql> explain select * from tbl_name where uid = 104460 and times > 38\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tbl_name
         type: ref
possible_keys: uid,times
          key: uid
      key_len: 4
          ref: const
         rows: 9
        Extra: Using where
1 row in set (0.00 sec)

挂了,还是只用到了uid索引,貌似还和MySQL的版本有一些关系,可以看看这篇博文http://www.alidba.net/index.php/archives/81

致歉,我传讹了,请大家更新”大脑数据库”,感谢xiaowei同学提醒,不知道的还很多,共同学习,一起进步。

Tags: ,

  1. One Response to “我也不知道的MySQL”

  2. By xiaowei on Mar 16, 2009 | Reply

    blog写的不错
    呵呵

Post a Comment