我有Mysql查询,像这样:

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`


查询速度非常慢(大约10秒)。没有这一部分的查询:
左外联接Extra_fields AS Extra0 ON Extra0Code = MainCodeExtra0Nf = 2
很快

有什么方法可以优化第一次查询?

最佳答案

您想在联接表上添加索引以帮助按Code和Nf查找值,然后添加Value列,以便它可以满足选择列表所需的列:

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


您可能会在Main.Code上添加索引而受益,这样它就可以按排序顺序读取表,而无需执行文件排序:

ALTER TABLE Main ADD KEY (Code);


我对您的查询运行了EXPLAIN并得到了以下信息:

*************************** 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


第一个表没有文件排序。我必须使用...FROM Main FORCE INDEX(Code)...,但这可能是因为我测试了表中没有行。

第二张表显示它正在使用仅索引访问方法(“额外:使用索引”)。我假设仅引用了Extra_fields中的三列,而所有其他列均来自Main

09-05 12:22
查看更多