【发布时间】:2014-01-14 22:31:06
【问题描述】:
我需要改进一个类似于以下的查询,它只是根据一些过滤执行计数,同时还加入第二个表。 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,它就会运行得非常快,但我确实需要加入其中,因为我可能需要根据作者表进行过滤。
任何人都可以通过建议更多可能有助于加快速度的索引来提供帮助。
【问题讨论】:
-
EXPLAIN说什么? -
请给我们完整的图片好吗? IE。如果您有索引,我们可以看看它们是什么以及您是如何定义它们的吗?
-
@MatW 我想我们可以看到索引!??!?!
-
@Strawberry 我指的是上面提到的复合索引,而不是我们可以看到的主键
-
索引 (b.author_id,b.date) 以外的任何内容都没有用(对于此特定查询)
标签: mysql sql performance join