且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在多列MySQL中加快SELECT ..LIKE查询?

更新时间:2023-01-29 15:12:22

索引不会加快查询的速度,因为对于文本列,索引通过从左开始索引N个字符来工作.当您喜欢'%text%'时,它不能使用索引,因为在文本之前可以有可变数量的字符.

An index wouldn't speed up the query, because for textual columns indexes work by indexing N characters starting from left. When you do LIKE '%text%' it can't use the index because there can be a variable number of characters before text.

您应该做的是根本不使用这样的查询.相反,您应该使用MySQL支持MyISAM表的类似FTS(全文搜索)的工具.自己为非MyISAM表创建这样的索引系统也很容易,您只需要一个单独的索引表,即可在实际表中存储单词及其相关ID.

What you should be doing is not use a query like that at all. Instead you should use something like FTS (Full Text Search) that MySQL supports for MyISAM tables. It's also pretty easy to make such indexing system yourself for non-MyISAM tables, you just need a separate index table where you store words and their relevant IDs in the actual table.

更新

全文搜索可用于具有MySQL 5.6+的InnoDB表.

Full text search available for InnoDB tables with MySQL 5.6+.