首页 > 解决方案 > 如何优化这个查询(PDO+MYSQL)

问题描述

我正在尝试优化与大约 500.000 行的表相关的查询。

它包含三个涉及小表的子查询 (200>rows<1000)。

现在,查看 phpmyadmin,执行时间大约为 0.9 秒,而使用 PHP 打印一些时间变量时,它增加到大约 2.2 秒。

我尝试使用索引,但使用子查询似乎破坏了索引利用率(查看 EXPLAIN 的结果)

SELECT `year`, `month`,`origin`, `destination`, `quantity`, LEFT(`hs_code` , 6) as code 
FROM table_x as tab WHERE (`origin` = (SELECT `code` FROM `table_y` as tab2 
WHERE tab2.`region_id`=1 AND tab2.`code`= tab.`origin`) AND `destination` = (SELECT `code` FROM `table_y` as tab2 WHERE tab2.`region_id`=1 AND tab2.`code`= tab.`destination`)) AND `hs_code` = (SELECT `code` FROM table_z WHERE `code`=tab.hs_code AND ((`type`='2' AND `sub_type`='1' ) OR (`type`='2' AND `sub_type`='2' ) OR (`type`='2' AND `sub_type`='3' ) OR (`type`='2' AND `sub_type`='4' ) OR (`type`='2' AND `sub_type`='5' ) OR (`type`='2' AND `sub_type`='6' )) LIMIT 1) AND export=1 AND `year`>=2016 AND (`year`<2019 OR (`year`=2019 AND `month`<=3)) ORDER BY `year` ASC, `month` ASC,`origin` ASC,`destination` ASC

这是解释输出

1PRIMARY tab ref export,table_x_index_origin,table_x_ind... export 1 const 188731 使用索引条件;使用哪里;使用文件排序

4 DEPENDENT SUBQUERY table_z ref code,tipologia code 767 tab.hs_code 6 使用 where

3 DEPENDENT SUBQUERY tab2 eq_ref PRIMARY,table_y_index PRIMARY 6 tab.destination 1 使用 where

2 DEPENDENT SUBQUERY tab2 eq_ref PRIMARY,table_y_index PRIMARY 6 tab.origin 1 使用 where

这是表结构:

id - 整数 | hs_code - VARCHAR | 出口- INT | 原产地 - CHAR | 目的地 - CHAR | 数量 - INT | 值 - INT | 年 - INT | 月 - INT

对我来说 0.9S 的执行时间会很好,但我无法以我尝试的任何方式在 PHP(使用 PDO)中实现该结果......

标签: mysqlsql

解决方案


推荐阅读