mysql - 如何优化这个查询(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)中实现该结果......
解决方案
推荐阅读
- xamarin.forms - 网格与 iOS 中的 ListView 重叠 - XamarinForms
- python - Dask:使用典型的 numpy 索引更新 dask 数组中的值时出现赋值错误
- c# - 我将 ulong 用于 100 的阶乘,但它仍然溢出
- python - Selenium 测试是否存在 CSS 类
- ios - UIImagePickerController 不压缩视频
- javascript - 尝试通过 Google App Scripts 将表单条目(从侧边栏)传递到 Google 表格中的特定列/单元格
- css - 无法使用 Bootstrap 上传背景图片
- php - 来自 xml 文件的 PHP 数组 - 获取未知的对象名称和属性
- javascript - 如何从 redux 商店获取状态的最新值?
- sql - SQL在没有ID的同一张表上选择int更新