简体   繁体   中英

Slow MySql query (optimizing LEFT OUTER JOIN)

I have Mysql query, something like this:

SELECT 
    Main.Code,
    Nt,
    Ss,
    Nac,
    Price,
    Ei,
    Quant,
    Dateadded,
    Sh,
    Crit,
    CAST(Ss * Quant AS DECIMAL (10 , 2 )) AS Qss,
    CAST(Price * Quant AS DECIMAL (10 , 2 )) AS Qprice,
    `Extra0`.`Value`
FROM
    Main
        LEFT OUTER JOIN
    `Extra_fields` AS `Extra0` ON `Extra0`.`Code` = `Main`.`Code`
        AND `Extra0`.`Nf` = 2
ORDER BY `Code`

The query is very slow (about 10 sec.). The query without this part: LEFT OUTER JOIN Extra_fields AS Extra0 ON Extra0 . Code = Main . Code AND Extra0 . Nf =2 is fast.

Is there some way to optimize first query?

You want to add an index on the joined table to help look up values by Code and Nf, then add the Value column so it can satisfy the column you need for the select-list:

ALTER TABLE Extra_fields ADD KEY (Code, Nf, Value);

You may benefit by adding an index on Main.Code so it reads the table in sorted order without having to do a filesort:

ALTER TABLE Main ADD KEY (Code);

I ran EXPLAIN on your query and got this:

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: Main
   partitions: NULL
         type: index
possible_keys: NULL
          key: Code
      key_len: 5
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: NULL
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: Extra0
   partitions: NULL
         type: ref
possible_keys: code
          key: code
      key_len: 10
          ref: test.Main.Code,const
         rows: 1
     filtered: 100.00
        Extra: Using index

The first table has no filesort. I had to use ...FROM Main FORCE INDEX(Code)... but it could be because I tested with no rows in the table.

The second table shows it is using an index-only access method ("Extra: Using index"). I assume only three columns from Extra_fields are referenced, and all other columns are from Main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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