0

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?

2
  • Create required index on Code and Nf columns Commented Jan 28, 2017 at 7:16
  • 1
    Please provide SHOW CREATE TABLE for both tables. Commented Jan 29, 2017 at 5:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Better yet, Extra_fields, since it smells like an EAV type schema, should have PRIMARY KEY(Code, Nf) and no AUTO_INCREMENT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.