有一个25万行的表test,有2个字符串字段:a和b,其中a带普通索引.a的值有五种"test1","test2","test3","test4","test5",各种分别5万行,随机散列在不同的行而不是连续的.执行语句:
explain select * from test where a = "test1" and b like "%测试%";
分析出的rows为50582,只比50000多了一点.
再执行语句:
explain select * from test where b like "%测试%";
分析出的rows为250000,等于总行数,说明进行了全表扫描.这样看起来似乎后面一个语句明显是更慢的,但是执行结果却是:
select * from test where a = "test1" and b like "%测试%";
0 rows in set (0.26 secs)select * from test where b like "%测试%";
0 rows in set (0.15 secs)后面一个全表扫描的语句反而更快,select语句加了索引条件过滤,执行效率反而比全表扫描更慢,这是怎么回事?

解决方案 »

  1.   

    select * from test where a = "test1" and b like "%测试%";
    0 rows in set (0.26 secs)
    1)Mysql用"%测试%"这样的形式在检索的时候不会用到索引,应该为"测试%";
    2)楼主的查询语句检索的是多个分离的行的集合,Mysql还是会顺序的检索整个表,没有用到索引,应该写为
    select * from test where a="test1"
    union
    select * from test where b like "%测试%";
      

  2.   

    select * from test where a = "test1" and b like "%测试%"

    select * from test where a="test1"
    union
    select * from test where b like "%测试%"
    是不同的吧?
      

  3.   

    不知道写为select * from test where b like "%测试%" and a = "test1"
    会不会结果不一样你测试一下看看
      

  4.   

    同意deepbluesea(Jeff) 兄的,
    select * from test where a = "test1" and b like "%测试%"

    select * from test where a="test1"
    union
    select * from test where b like "%测试%"
    肯定是不同的!但是linanbox21(java学习中) 说的前面部分还是有道理的!