在具有许多行(250m +行)的表上选择查询

时间:2018-11-29 17:31:33

标签: mysql sql query-performance

我有一条select语句,要花一段时间(很长的时间)才能完成MySQL。所有表均为“ MyISAM”。 MySQL版本是5.6.41。

我有三个桌子

  • 表1:50,000行
  • 表2:7,500,000行(7.5GB)
  • 表3:250,000,000行(17.5GB)

我在表的左连接处执行一条select语句。

select `table1`.* 
from `table1`  
inner join `table2` on `table2`.`table1_id` = `table1`.`id` 
inner join `table3` on `table3`.`table2_id` = `table2`.`id` 
where `table1`.`id` = "2" and `table3`.`parameter` = 'param' 

“ id”列是主键,“ parameter”列已应用索引

当前表格代码

CREATE TABLE `table1` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`id`), 
    INDEX `id` (`id`), 
)
COLLATE='utf8_unicode_ci'
ENGINE=MyISAM;

CREATE TABLE `table2` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 
    `table1_id` INT(10) UNSIGNED NOT NULL,
    PRIMARY KEY (`id`), 
    INDEX `id` (`id`), 
    INDEX `table1_id_index` (`table1_id`),
)
COLLATE='utf8_unicode_ci'
ENGINE=MyISAM;


CREATE TABLE `table3` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 
    `table2_id` INT(10) UNSIGNED NOT NULL,
    `parameter` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
    PRIMARY KEY (`id`), 
    INDEX `id` (`id`), 
    INDEX `id` (`parameter`), 
    INDEX `table2_id_index` (`table1_id`),
)
COLLATE='utf8_unicode_ci'
ENGINE=MyISAM;

奇怪的是,当我以其他方式重新编写查询时,我没有性能问题:

select `table1`.* 
from `table3`  
inner join `table2` on `table3`.`table2_id` = `table2`.`id` 
inner join `table1` on `table2`.`table1_id` = `table1`.`id` 
where `table1`.`id` = "2" and `table3`.`parameter` = 'param' 

2 个答案:

答案 0 :(得分:0)

确保您具有正确的ID索引,并确保您不执行无用的数据转换 和

Bag Attributes
    Microsoft Local Key set: <No Values>
    localKeyID: 
    friendlyName: 
    Microsoft CSP Name: 
    X509v3 Key Usage: 10 
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG...
-----END PRIVATE KEY-----
Bag Attributes
   ...
-----BEGIN CERTIFICATE-----
MIIHQzCCBiugAwIBAgIQDEtIx...
-----END CERTIFICATE-----

答案 1 :(得分:0)

切换到InnoDB。它将“ PRIMARY KEY”与数据“聚类”,从而避免了MyISAM带来的几次随机寻找。

同时,key_buffer_size的值是什么?你有多少内存?