How to make JOIN query use index?

前端 未结 6 1783
无人共我
无人共我 2021-02-07 04:49

I have two tables:

CREATE TABLE `articles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(1000) DEFAULT NULL,
  `last_updated` datetime DEFAULT NULL         


        
6条回答
  •  你的背包
    2021-02-07 05:33

    Use of a non-covering index is expensive. For each row, any uncovered columns have to be retrieved from the base table, using the primary key. So I'd first try to make the index on articles covering. That might help convince the MySQL query optimizer that the index is useful. For example:

    KEY IX_Articles_last_updated (last_updated, id, title, comment_cnt, deleted),
    

    If that doesn't help, you could play around with FORCE INDEX:

    SELECT  a.*
    FROM    article_categories AS c FORCE INDEX (IX_Articles_last_updated)
    JOIN    articles AS a FORCE INDEX (PRIMARY)
    ON      a.id = c.article_id
    WHERE   c.category_id = 78
            AND a.comment_cnt > 0
            AND a.deleted = 0
    ORDER BY 
            a.last_updated
    LIMIT   100, 20
    

    The name of the index enforcing the primary key is always "primary".

提交回复
热议问题