【问题标题】:Mysql improve performance of count with joinMysql 通过加入提高计数的性能
【发布时间】: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


【解决方案1】:

您总是需要索引外键字段以及主键字段。

【讨论】:

  • +1 但比这更糟。他有author_id 作为外键,甚至没有定义它。
  • 我给出的例子不是真正的查询,只是一个例子。您可以认为author_id 上存在外键关系,如问题中所述。
  • Hwever 一个 Fk 并不意味着有一个索引
  • 我认为是因为我使用了innoDB存储引擎。
猜你喜欢
  • 1970-01-01
  • 2016-10-24
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多