最近看Mysql优化方法的材料,很多材料提到说再做表连接时,即使连接的字段都带着索引,但如果字段定义不匹配,如一个char(10),一个char(15),那么mysql将不会用索引直接处理,但是我试了一下材料上剧的例子,explain察看连接的type是eq_ref而不是材料说上的all。我的Mysql是5.0 。5la版本的,是Mysql已经把这个问题优化了吗

解决方案 »

  1.   

    应该还没有被优化,因为在mysql 5.1 的手册中还有保留着这个说法。或者你能提供你的create table 语句以及查询语句,这样,大家可以一起来分析 一下。
      

  2.   

     CREATE TABLE `user` (
      `user_name` varchar(255) NOT NULL,
      `password` varchar(255) NOT NULL,
      `email` varchar(255) NOT NULL,
      PRIMARY KEY  (`user_name`),) ENGINE=MyISAM DEFAULT CHARSET=utf8;CREATE TABLE `admin_user` (
      `user_name` varchar(50) NOT NULL,
      `admin_type` char(1) NOT NULL default '1',
      UNIQUE KEY `user_name` (`user_name`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
    user_name一个varchar(255),一个50,符合手册上说的列定义不匹配,
     explain select * from admin_user as a , user as u where a.user_name=u.user_name;
    结果
     id | select_type | table | type   | possible_keys | key     | key_len | ref             | rows | Extra       |
    +----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------------+
    |  1 | SIMPLE      | a     | ALL    | user_name     | NULL    | NULL    | NULL            |   19 |             | 
    |  1 | SIMPLE      | u     | eq_ref | PRIMARY       | PRIMARY | 767     | cc9.a.user_name |    1 | Using where 我看手册上举的例子也是一个表的主键和另一个表带索引的列关联,不知道为什么我这里是eq_ref
      

  3.   

    用你的表做了个试验,的确是你的说的这种情况,
    然后又查了一下手册。

    One problem here is that MySQL can use indexes on columns more efficiently if they are declared as the same type and size. In this context, VARCHAR and CHAR are considered the same if they are declared as the same size. tt.ActualPC is declared as CHAR(10) and et.EMPLOYID is CHAR(15), so there is a length mismatch. 
    手册上的情况和你的不太一样,手册上所指的是MYSQL如果在不同的索引中进行优化选择。而我们现这测试的这个例子中其实MYSQL已经别无选择,只有这么个索引可用。