2016-02-05 65 views
0

如果我仍然使用MySQL而不是MySQLI,表示抱歉。将尽快升级,但目前我需要找到解决这个问题的方法。改进MySQL查询

我有一个查询,我认为已经优化,这显然不是。

我在水果表小于200行但它的查询需要约15秒即可完成

下面是该查询:

SELECT `o`.`fruits_id` FROM `fruits` as `o` 
JOIN `fruits_categories` as `oc` ON `o`.`fruits_id` = `oc`.`fruits_id` 
JOIN `categories` as `c` ON `c`.`fru_id` = `oc`.`fru_id` 
WHERE ((o.fruits_name LIKE '%apple orange%' OR o.fruits_description LIKE '%apple orange%' OR o.instagram_tag LIKE '%apple orange%' OR c.cat_name LIKE '%apple orange%' OR p.price_name LIKE '%apple orange%') 
OR ((o.fruits_name LIKE '%apple%' OR o.fruits_description LIKE '%apple%' OR o.instagram_tag LIKE '%apple%' OR c.cat_name LIKE '%apple%' OR p.price_name LIKE '%apple%') 
AND (o.fruits_name LIKE '%orange%' OR o.fruits_description LIKE '%orange%' OR o.instagram_tag LIKE '%orange%' OR c.cat_name LIKE '%orange%' OR p.price_name LIKE '%orange%'))) 
GROUP BY `o`.`fruits_id` 

我担心的是,当数据库的增长,搜索将无法使用,因为它可能需要永久。

所有帮助表示赞赏。

+0

这么多类似查询会降低性能 –

回答

1
  1. 所有LIKE '%apple orange%'条件是不必要的,它们被用于单个词的条件覆盖。
  2. like '%whatever%'条件不能使用索引。考虑在受影响的列上创建fulltext index,并使用match(...) against(...)全文搜索而不是like运算符进行模式匹配。
0

什么明显放缓这个查询是“LIKE”

而且它是一个有点多余搜索“%苹果橘子%”或(“%苹果%”和“%橙色%”)删除'%apple orange%'搜索。

0

随着时间的推移,你一定会遇到像%phrase%这样的查询性能问题。请注意,对于不以%开头的查询,您可以使用B-tree索引。 所以,你有几种选择:

  1. 尝试重写您的查询,以便检索词不%启动(如果您的应用程序允许),并使用B树索引。更多信息:http://dev.mysql.com/doc/refman/5.7/en/index-btree-hash.html
  2. 尝试全文索引 https://dev.mysql.com/doc/refman/5.7/en/fulltext-search.html 请注意,InnoDb表在早期版本中是不可能的。但如果你的桌子快速增长,那么你很可能迟早会遇到麻烦。
  3. 最具扩展性的方法是将此匹配逻辑移入专门为此设计的第三方应用程序(如http://sphinxsearch.com/)。