Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql通过join提高count的性能_Mysql_Sql_Performance_Join - Fatal编程技术网

Mysql通过join提高count的性能

Mysql通过join提高count的性能,mysql,sql,performance,join,Mysql,Sql,Performance,Join,我需要改进一个类似于以下内容的查询,该查询在加入第二个表的同时,仅根据一些筛选执行计数。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

我需要改进一个类似于以下内容的查询,该查询在加入第二个表的同时,仅根据一些筛选执行计数。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');
一旦我删除了连接,它就会运行得非常快,但是我确实需要在那里加入连接,因为我可能需要根据author表进行过滤


任何人都可以通过建议更多的索引来帮助加快速度。

你总是需要索引外键字段和主键字段。

解释什么说什么?我们可以了解整个情况吗?也就是说,如果你有索引,我们可以看到它们是什么以及你是如何定义它们的吗?@MatW我想我们可以看到索引@我的意思是提到的复合索引,而不是我们可以看到的主键索引(b.author\u id,b.date)以外的任何东西都不会有用(对于这个特定的查询)+1,但它比这更糟糕。他将
author\u id
作为外键,甚至没有将其定义为外键。我给出的示例不是真正的查询,只是一个示例。您可以认为,如问题中所述,
author\u id
上存在外键关系。但是,Fk并不意味着存在索引。我认为这与我使用innoDB存储引擎的情况相同。