简体   繁体   English

MySQL慢查询:如何优化以下查询?

[英]MySQL Slow Query: How to optimize the following query?

Following is the query that i am using: 以下是我正在使用的查询:

SELECT *
FROM (
    SELECT 
        (
            CASE WHEN product_name like '%word1%' THEN 1 ELSE 0 END +
            CASE WHEN product_name like '%word2%' THEN 1 ELSE 0 END +
            CASE WHEN product_name like '%word3%' THEN 1 ELSE 0 END
        ) AS numMatches
    FROM products as p 
   ) as derived
WHERE numMatches > 0
ORDER BY numMatches DESC
LIMIT 30,10

I added an index (BTREE) on product_name, there are 3 million records in the column, the query is executing in 3-5 seconds. 我在product_name上添加了一个索引(BTREE),该列中有300万条记录,查询在3-5秒内执行。

Explain says 'Using where; 解释说:“在哪里使用; Using filesort' so i can figure out its not using the index. 使用filesort',这样我可以弄清楚它不使用索引。

No, it's not using the index. 不,它没有使用索引。

For that, you would have to compare with 'word1%', 'word2%', etc.. but doesn't work when you use the joker at the beginning. 为此,您必须将其与“ word1%”,“ word2%”等进行比较。但是,当您一开始使用小丑时,它就不起作用。

But, If your mysql version is relatively modern you can use fulltext indexes, which would serve for your query. 但是,如果您的mysql版本相对较新,则可以使用全文索引,这将为您的查询服务。

https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html

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

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