重现一条简单SQL的优化过程

  • GreatSQL社区原创内容未经授权不得随意使用,转载请联系小编并注明来源。
  • GreatSQL是MySQL的国产分支版本,使用上与MySQL一致。
  • 作者:  JennyYu
  • 文章来源:GreatSQL社区投稿
  • 背景

    接到客户诉求说一条SQL长时间运行不出结果,让给看看怎么回事,SQL不复杂,优化措施也不复杂,但是要想SQL达到最优状态,也是需要经过一番考量并做出选择的。下面借实验还原一下此SQL优化过程。

    实验:

    数据库环境:MySQL5.7.39

    测试表结构如下:

    mysql> show create table t_1G *************************** 1. row *************************** Table: t_1 Create Table: CREATE TABLE `t_1` ( `w_id` int(11) DEFAULT NULL, `w_name` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 1 row in set (0.00 sec) mysql> show create table t_2G *************************** 1. row *************************** Table: t_2 Create Table: CREATE TABLE `t_2` ( `i_id` int(11) NOT NULL, `i_name` varchar(24) DEFAULT NULL, `i_price` decimal(5,2) DEFAULT NULL, `i_data` varchar(50) DEFAULT NULL, `i_im_id` int(11) NOT NULL, PRIMARY KEY (`i_im_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 1 row in set (0.00 sec) mysql> show create table t_3G *************************** 1. row *************************** Table: t_3 Create Table: CREATE TABLE `t_3` ( `s_w_id` int(11) NOT NULL, `s_i_id` int(11) NOT NULL, `s_quantity` int(11) DEFAULT NULL, `s_ytd` int(11) DEFAULT NULL, `s_order_cnt` int(11) DEFAULT NULL, `s_remote_cnt` int(11) DEFAULT NULL, `s_data` varchar(50) DEFAULT NULL, `s_dist_01` char(24) DEFAULT NULL, `s_dist_02` char(24) DEFAULT NULL, `s_dist_03` char(24) DEFAULT NULL, `s_dist_04` char(24) DEFAULT NULL, `s_dist_05` char(24) DEFAULT NULL, `s_dist_06` char(24) DEFAULT NULL, `s_dist_07` char(24) DEFAULT NULL, `s_dist_08` char(24) DEFAULT NULL, `s_dist_09` char(24) DEFAULT NULL, `s_dist_10` char(24) DEFAULT NULL, `t_2_id` int(11) DEFAULT NULL, `t_1_id` int(11) DEFAULT NULL, PRIMARY KEY (`s_w_id`,`s_i_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 1 row in set (0.00 sec) Create Table: CREATE TABLE `t_4` ( `w_name` varchar(10) DEFAULT NULL, `s_i_id` int(11) NOT NULL, `s_quantity` int(11) DEFAULT NULL, `s_ytd` int(11) DEFAULT NULL, `s_order_cnt` int(11) DEFAULT NULL, `s_remote_cnt` int(11) DEFAULT NULL, `s_data` varchar(50) DEFAULT NULL, `t_2_id` int(11) DEFAULT NULL, `i_name` varchar(24) DEFAULT NULL, `i_price` decimal(5,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4