【问题标题】:Optimizing this MySQL Query优化这个 MySQL 查询
【发布时间】:2012-04-20 16:41:33
【问题描述】:

表架构

对于这两个表,CREATE 查询如下:

表 1:(file_path_key,dir_path_key)

create table Table1(
             file_path_key varchar(500), 
             dir_path_key varchar(500), 
             primary key(file_path_key)) 
engine = innodb;

Table2:(file_path_key,hash_key)

create table Table2(
             file_path_key varchar(500) not null, 
             hash_key bigint(20) not null, 
             foreign key (file_path_key) references Table1(file_path_key) on update cascade on delete cascade)
engine = innodb;

目标

给定一个 file_path F 和它的 dir_path 字符串 D,我需要找到所有这些 F 的散列集合中至少有一个散列的文件名,但是 不要将它们的目录名称作为 D。如果一个文件 F1 共享多个哈希 用F,那么应该重复那么多次。

注意,Table1 中的 file_path_key 列和 Table2 中的 hash_key 列都被索引了。

在这种特殊情况下,Table1 有大约 350,000 个条目,Table2 有 31,167,119 个条目,这使得我当前的查询很慢:

create table temp 
        as select hash_key from Table2 
        where file_path_key = F;

select s1.file_path_key 
        from Table1 as s1 
        join Table2 as s2 
        on s1.file_path_key join 
        temp on temp.hash_key = s2.hash_key 
        where s1.dir_path_key != D

如何加快查询速度?

【问题讨论】:

  • 您的问题是“如何优化我当前的查询?”?无论如何,请告诉我们您真正想要解决的问题。
  • 是的,JamWaffles,我想加快速度!

标签: mysql sql query-optimization


【解决方案1】:

我不明白temp 表的用途是什么,但请记住,使用 CREATE .. SELECT 创建的此类表没有任何索引。因此,至少将该语句修复为

CREATE TABLE temp (INDEX(hash_key)) ENGINE=InnoDB AS 
SELECT hash_key FROM Table2 WHERE file_path_key = F;

否则另一个 SELECT 与 temp 执行完全连接,所以它可能会很慢。

我还建议在 Table1 中使用数字主键(INT、BIGINT)并从 Table2 而不是文本列中引用它。例如:

create table Table1(
             id int not null auto_increment primary key,
             file_path_key varchar(500), 
             dir_path_key varchar(500), 
             unique key(file_path_key)) 
engine = innodb;

create table Table2(
             file_id int not null, 
             hash_key bigint(20) not null, 
             foreign key (file_id) references Table1(id) 
            on update cascade on delete cascade) engine = innodb;

如果在连接谓词中使用整数列而不是文本列,则连接两个表的查询可能会快很多。

【讨论】:

  • Mushu,那需要我像以前一样添加索引吗?
猜你喜欢
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 2017-02-20
  • 1970-01-01
相关资源
最近更新 更多