Which is faster — INSTR or LIKE?

前端 未结 4 1874
广开言路
广开言路 2020-11-29 23:04

If your goal is to test if a string exists in a MySQL column (of type \'varchar\', \'text\', \'blob\', etc) which of the following is faster / more efficient / better to use

4条回答
  •  猫巷女王i
    2020-11-29 23:52

    FULLTEXT searches are absolutely going to be faster, as kibibu noted in the comments above.

    However:

    mysql> select COUNT(ID) FROM table WHERE INSTR(Name,'search') > 0;
    +-----------+
    | COUNT(ID) |
    +-----------+
    |     40735 | 
    +-----------+
    1 row in set (5.54 sec)
    
    mysql> select COUNT(ID) FROM table WHERE Name LIKE '%search%';
    +-----------+
    | COUNT(ID) |
    +-----------+
    |     40735 | 
    +-----------+
    1 row in set (5.54 sec)
    

    In my tests, they perform exactly the same. They are both case-insensitive, and generally they perform full-table scans, a general no-no when dealing with high-performance MySQL.

    Unless you are doing a prefix search on an indexed column:

    mysql> select COUNT(ID) FROM table WHERE Name LIKE 'search%';
    +-----------+
    | COUNT(ID) |
    +-----------+
    |         7 | 
    +-----------+
    1 row in set (3.88 sec)
    

    In which case, the LIKE with only a suffix wildcard is much faster.

提交回复
热议问题