[英]Mysql improve performance of count with 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');
一旦我刪除了聯接,它就會非常快速地運行,但是我確實需要在那里的聯接,因為我可能需要根據author表進行過濾。
任何人都可以通過建議更多可能有助於加快速度的索引來提供幫助。
您始終需要索引外鍵字段以及主鍵字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.