代码之家  ›  专栏  ›  技术社区  ›  Maximus

优化mysql中的三个表连接

  •  0
  • Maximus  · 技术社区  · 14 年前

    我正在构建一个电子库,我已经编写了一个查询,该查询会扫描更多的行,这可能是由于索引不好。这是我的桌子结构。

    1. book_categories (cat_id,parent_id default空,cat_name,parent_cat_name default空)
    2. authors (作者ID,作者姓名,活动)
    3. books (book_id,cat_id,author_id,book_title,book_contents,book_status enum(published,pending,deleted)发布日期)

    这是SQL代码

      SELECT T.author_id, 
             T.author_name, 
             C.parent_id, 
             C.cat_id, 
             C.cat_name, 
             B.book_id, 
             B.book_title, 
             B.book_contents, 
             B.publish_date 
        FROM books B, 
             authors T, 
             book_categories C 
       WHERE B.author_id = T.author_id 
         AND C.cat_id = B.cat_id 
         AND book_status = 'published' 
    ORDER BY published_date DESC
    

    解释上述问题

    id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
    -----------------------------------------------------------------------------------------------------
    1   SIMPLE  C   ALL     PRIMARY     NULL    NULL    NULL    449     Using where; Using temporary; Using filesort
    1   SIMPLE  B   ref     author_id,cat_id    cat_id  4   bookdb.C.cat_id     214     Using where
    1   SIMPLE  T   eq_ref  PRIMARY     PRIMARY     4   bookdb.B.author_id  1    
    

    索引和键

    Alter table books 
    add Foreign Key (author_id) references authors (author_id) on delete  restrict on update  restrict;
    
    Alter table books 
    add Foreign Key (cat_id) references book_categories (cat_id) on delete  restrict on update  restrict;
    
    Create Index books_INX ON books(cat_id,book_status,published_date);
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   Vince Bowdren    14 年前

    你的索引很好。只要扫描速度快,就不用担心扫描几百行(约占表的0.5%)。够快吗?

        2
  •  0
  •   Icarus    14 年前

    我没有看到在那些表上创建任何索引…如果没有索引,就不要指望mysql会“即时”创建并使用它们。定义一些怎么样?

    http://dev.mysql.com/doc/refman/5.0/en/create-index.html

        3
  •  0
  •   Juha Syrjälä    14 年前

    尝试添加 author_id 索引 books_INX . 试着移动 published_date 到不同的地方(第一,最后…) 书刊 . 例如:

    Create Index books_INX ON books(cat_id,author_id,book_status,published_date);
    

    确保 授权人 cat_id 是的主键 author book_category 分别是桌子。阿尔索 book_id 应该是 books 表,即使它不应该影响这个特定的查询。