Mysql通过join提高了count的性能

时间:2014-01-14 22:31:06

标签: mysql sql performance join

我需要改进类似于以下内容的查询,该查询仅基于某些过滤执行计数,同时还加入第二个表。书籍表可能有数百万条记录。

CREATE TABLE author
    (id int auto_increment primary key, name varchar(20), style varchar(20));


CREATE TABLE books
(
    id int auto_increment primary key not null,
    author_id int not null, 
    title varchar(20) not null, 
    level int not null, 
    date datetime not null, 
    CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES author(id)
);

CREATE INDEX idx_level_date ON books(level, date);

INSERT INTO author
    (name, style)
VALUES
    ('John', 'Fact'),
    ('Sarah', 'Fact'),
    ('Michael', 'Fiction');


INSERT INTO books
    (id, author_id, title, level, date)
VALUES
    (1, 1, 'John Book 1', 1, '2012-01-13 13:10:30'),
    (2, 1, 'John Book 2', 1, '2011-03-12 12:10:20'),
    (3, 1, 'John Book 3', 2, '2012-01-23 12:40:30'),
    (4, 2, 'Sarah Book 1', 1, '2009-10-15 13:10:30'),
    (5, 2, 'Sarah Book 2', 2, '2013-01-30 12:10:30'),
    (6, 3, 'Michael Book 1', 3, '2012-11-13 12:10:30');

删除加入后,它会非常快速地运行,但我确实需要加入,因为我可能需要根据作者表进行过滤。

任何人都可以通过建议可能有助于加快速度的索引来提供帮助。

1 个答案:

答案 0 :(得分:1)

您始终需要索引外键字段以及主键字段。