数据库
首页 > 数据库> > MySQL:ORDER BY子句减慢MATCH AGAINST搜索速度

MySQL:ORDER BY子句减慢MATCH AGAINST搜索速度

作者:互联网

我有以下MySQL查询:

$sql = "SELECT (SELECT COUNT(share_id) FROM pd_shares WHERE section = 'news' AND item_id = news.article_id) AS count_shares, article_id, link, title, publish_date, description, source FROM pd_news AS news WHERE (MATCH (title_ascii, description_ascii) AGAINST ('".match_against($_GET["sn"])."' IN BOOLEAN MODE)) AND article_id > " . $last_index . " ORDER BY article_id ASC LIMIT 0,$limit";

当我进行搜索时,查询使用ORDER BY子句加载513.24 ms.当我删除它时,它运行77.12毫秒.

title_ascii和description_ascii都是FULLTEXT.

如何重写此查询以使运行速度加载速度比目前快得多?

EXPLAIN输出:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   PRIMARY     news    fulltext    PRIMARY,news_search     news_search     0   NULL    1   Using where; Using filesort
2   DEPENDENT SUBQUERY  pd_shares   ref     section     section     19  const,my_database.news.article_id   2   Using index condition

解决方法:

了解引用表的模式(pd_shares和pd_news)会很有帮助.我将子选择移动到普通连接并添加了group by子句:

$sql = "SELECT
          article_id
        , link
        , title
        , publish_date
        , description
        , source 
        , COUNT(shares.share_id) AS count_shares
        FROM pd_news AS news 
        LEFT JOIN pd_shares shares
            ON shares.section = 'news' AND shares.item_id = news.article_id
        WHERE (MATCH (title_ascii, description_ascii) AGAINST ('".match_against($_GET["sn"])."' IN BOOLEAN MODE)) 
            AND article_id > " . $last_index . " 
        GROUP BY article_id
        ORDER BY article_id ASC LIMIT 0, $limit";

标签:mysql,sql,sql-order-by,match-against
来源: https://codeday.me/bug/20190711/1431531.html