2016-02-05 64 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/)。