简体   繁体   English

使用左联接和子查询优化MySQL查询

[英]Optimising a MySQL query with a Left Join and a sub-query

I've got a number of queries like this... 我有很多这样的查询...

SELECT colA, colB, colC, colD FROM table1 
  LEFT JOIN (
    SELECT colD FROM table2 WHERE colE = 3225 
  ) AS subquery
ON colD = colA ;

Which get listed in my server's "log-queries-not-using-indexes" log. 哪些列在我的服务器的“ log-queries-not-using-indexes”日志中。

The EXPLAIN looks like this... EXPLAIN看起来像这样...

id | select_type | table      | type  | possible_keys | key     | key_len | ref  | rows | Extra
---+-------------+------------+-------+---------------+---------+---------+------+------+-------------
 1 | PRIMARY     | table1     | range | PRIMARY       | PRIMARY | 3       | NULL |   58 | Using where
 1 | PRIMARY     | <derived2> | ALL   |          NULL |    NULL |    NULL | NULL |    1 | 
 2 | DERIVED     | table2     | const | PRIMARY       | PRIMARY | 3       |      |    1 | 

Is there any way i can restructure the Query, or are there any new indexes I should add to improve this? 有什么方法可以重组查询,还是应该添加任何新索引来改善此情况?

FYI the Tables are structured like this... 仅供参考,表格的结构如下:

CREATE TABLE `table1` (
 `colA` MEDIUMINT( 9 ) NOT NULL ,
 `colB` VARCHAR( 100 ) DEFAULT NULL ,
 `colC` VARCHAR( 6 ) DEFAULT NULL ,
 some more columns removed to simplify things...
 PRIMARY KEY (  `colA` ) ,
 KEY  `colB` (  `colB` ) ,
 KEY  `colC` (  `colC` ) 
) ENGINE = MYISAM DEFAULT CHARSET = latin1 ;


CREATE  TABLE `table2` (
 `colE` mediumint( 9  )  NOT  NULL  auto_increment ,
 `colD` mediumint( 9  ) default  '0',
 some more columns removed to simplify things...
 PRIMARY  KEY (  `colE`  ) ,
 KEY  `colD` (  `colD`  )  
) ENGINE  =  MyISAM  DEFAULT CHARSET  = latin1 ;

Thanks in advance, 提前致谢,

Yours 你的

phil 菲尔

I would try the following: 我会尝试以下方法:

SELECT ColA, ColB, ColC, ColD
FROM
    table1
    LEFT JOIN table2
        ON ColE = 3225
        AND ColD = ColA

Also, try creating an index that covers both ColE and ColD on table2 : 另外,尝试在table2上创建一个同时覆盖ColEColD的索引:

CREATE INDEX `IDX_table2` on `table2` (`colE` ASC, `colD` ASC);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM