MySQL Query does not use index in table join

前端 未结 2 2021
迷失自我
迷失自我 2020-12-19 03:58

I am trying to list all the book_sales information for a particular book author. So I have a query and it\'s not using Index to lookup records.

The followin

相关标签:
2条回答
  • 2020-12-19 04:18

    Try this

    SELECT sale_amount, price
    FROM book_sales,books
    LEFT JOIN books ON(book_sales.book_id = books.book_id)
    WHERE books.author_id =1
    
    0 讨论(0)
  • 2020-12-19 04:29

    As you can see in the EXPLAIN, "book_id" is listed as a possible key. If MySQL doesn't use it, it's just that the optimizer doesn't think it would speed up the query. Which is true if "book_sales" only has 2 rows, and 100% of those rows share the same "book_id". It's called cardinality btw. How to Avoid Table Scans (MySQL Manual)

    Try filling it with more rows and you should see that MySQL will use an index for the join.

    Edit: the query

    SELECT sale_amount, price
    FROM books, book_sales
    FORCE INDEX ( book_id ) 
    WHERE book_sales.book_id = books.book_id
    AND books.author_id =1
    

    ...will not work either in that case because the optimizer still recognizes that reading the index is suboptimal and switches the table order to avoid doing so. You can force the table order by using STRAIGHT_JOIN. This is, however, a bit of a hack because it forces MySQL to execute the query in a way that is not the best.

          EXPLAIN
           SELECT sale_amount, price
             FROM books
    STRAIGHT_JOIN book_sales FORCE INDEX (book_id) ON book_sales.book_id = books.book_id
            WHERE books.author_id = 1
    
    0 讨论(0)
提交回复
热议问题