简体   繁体   English

MySQL搜索优化以获得更好的性能

[英]MySQL Search optimisation for better performance

I have an array with a list of keywords, 我有一个包含关键字列表的数组,

$arr = array('london','england','football',...);

The array could have N th keywords. 该数组可以有 N 关键字。

I need to use this on a sql query but i dont want to do too many repetitions like this. 我需要在sql查询中使用它,但我不想做这样的太多重复。

select * from t1 where title LIKE('%$arr[0]%') OR title LIKE('%$arr[1]%') [...]

just need a better solution as each keyword filters out the records. 只需要一个更好的解决方案,因为每个关键字过滤掉记录。

thnx 日Thnx

One solution would be to create a lookup table that is populated with the rowid and keywordid whenever a row is created or changed. 一种解决方案是创建一个查找表,每当创建或更改行时,该查找表都使用rowid和keywordid填充。

Then you can skip all the LIKE and get much more performance. 然后你可以跳过所有的LIKE并获得更多的性能。

A trigger on insert and update should work but it will cost a little more performance on insert and update. 插入和更新的触发器应该可以工作,但在插入和更新时会花费更多的性能。

You would just use 你只需要使用

SELECT * FROM t1 WHERE id in (SELECT id FROM lookup WHERE keywordid IN ())

And if the keywords are many you could use a sub query more to get the keyword id's or if fewer use a cached lookup structure directly in code, dictionary or likewise. 如果关键字很多,您可以使用更多的子查询来获取关键字ID,或者更少使用直接在代码,字典或类似中使用缓存查找结构。

I'm unsure whether you wanted to optimize the actual query itself or the means to insert keywords into the query. 我不确定您是想优化实际查询本身还是要在查询中插入关键字的方法。 If it's the latter, then what comes to mind quickly is: 如果是后者,那么很快就会想到的是:

$query = "SELECT * FROM t1 WHERE title";

foreach($arr as $keyword)
{
    $stack[] = " LIKE '%$keyword%' ";
}

$query .= implode(' OR title ', $stack);

If you want to avoid full table scans based on keywords, that requires a different topic in itself with more explanation at your end. 如果您想避免基于关键字的全表扫描,那么本身需要一个不同的主题,并在您的最后提供更多解释。

Depending on the kind (and amount) of searches you'll be doing, you might need to consider using something else than pure-MySQL for that. 根据您将要进行的搜索的种类(和数量) ,您可能需要考虑使用除了纯MySQL之外的其他内容。

MySQL by itself is not quite well-suited when it comes to fulltext search : 在全文搜索方面,MySQL本身并不是很适合:

  • Using like '%...%' will result in bad performances (scanning all the lines of your table) 使用like '%...%'会导致糟糕的表现(扫描你桌子的所有线条)
  • Using a FULLTEXT index means using MyISAM as storage engine. 使用FULLTEXT索引意味着使用MyISAM作为存储引擎。


If you need to do a lot of searches, it might become more interesting to invest in a solution dedicated to indexing/searching through text, like Solr , or Sphinx . 如果您需要进行大量搜索,那么投资专用于索引/搜索文本的解决方案(如SolrSphinx)可能会变得更有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM