我需要改进类似于以下的查询,它仅根据某些过滤执行计数,同时还连接第二个表。 books 表可能有数百万条记录。
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');
一旦我删除了 join 它运行得非常快,但我真的需要在那里加入,因为我可能需要根据作者表进行过滤。
任何人都可以通过建议可能有助于加快速度的更多索引来提供帮助。
最佳答案
您始终需要索引外键字段以及主键字段。
关于Mysql 通过 join 提高 count 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21125409/