Mysql查询工作很慢怎么可以优化查询?

时间:2018-04-30 06:59:14

标签: mysql phpmyadmin query-optimization

查询:

SELECT
  `item`.*,
  GROUP_CONCAT(DISTINCT category.English_name) AS category,
  GROUP_CONCAT(DISTINCT item_color.Color) AS Color,
  GROUP_CONCAT(
    DISTINCT sub_category.English_name
  ) AS Sub_category,
  GROUP_CONCAT(DISTINCT unit.Name) AS Unit,
  GROUP_CONCAT(DISTINCT item_unit.Value) AS Unit_value,
  `gst`.`HSN` AS `GST_hsn`,
  `base_unit`.`Name` AS `Base_unit`
FROM
  `item`
LEFT JOIN
  `gst` ON `gst`.`ID` = `item`.`GST_hsn`
LEFT JOIN
  `item_category` ON `item_category`.`Item` = `item`.`ID`
LEFT JOIN
  `category` ON `category`.`ID` = `item_category`.`Category`
LEFT JOIN
  `item_color` ON `item_color`.`Item` = `item`.`ID`
LEFT JOIN
  `item_sub_category` ON `item_sub_category`.`Item` = `item`.`ID`
LEFT JOIN
  `sub_category` ON `sub_category`.`ID` = `item_sub_category`.`Sub_category`
LEFT JOIN
  `item_unit` ON `item_unit`.`Item` = `item`.`ID`
LEFT JOIN
  `unit` ON `unit`.`ID` = `item_unit`.`Unit`
LEFT JOIN
  `unit` AS `base_unit` ON `base_unit`.`ID` = `item`.`Base_unit`
WHERE
  `item`.`Status` = 'Open'
GROUP BY
  `item`.`ID`

如果您想访问架构。请访问sqlfiddle上的DB模式。

  

http://sqlfiddle.com/#!9/c1b1e0/1

我有超过1500行,执行时差不多5秒如何优化此查询,因此此查询的时间不到1秒。

1 个答案:

答案 0 :(得分:0)

多个多对多表中缺少合适的索引是一个重要的性能问题。按照

中的建议

http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

这样做。 (当然,请根据您的特定表名和列名进行调整。)

CREATE TABLE XtoY (
    # No surrogate id for this table
    x_id MEDIUMINT UNSIGNED NOT NULL,   -- For JOINing to one table
    y_id MEDIUMINT UNSIGNED NOT NULL,   -- For JOINing to the other table
    # Include other fields specific to the 'relation'
    PRIMARY KEY(x_id, y_id),            -- When starting with X
    INDEX      (y_id, x_id)             -- When starting with Y
) ENGINE=InnoDB;

注意:

⚈  Lack of an AUTO_INCREMENT id for this table -- The PK given is the 'natural' PK; there is no good reason for a surrogate.
⚈  "MEDIUMINT" -- This is a reminder that all INTs should be made as small as is safe (smaller ⇒ faster). Of course the declaration here must match the definition in the table being linked to.
⚈  "UNSIGNED" -- Nearly all INTs may as well be declared non-negative
⚈  "NOT NULL" -- Well, that's true, isn't it?
⚈  "InnoDB" -- More effecient than MyISAM because of the way the PRIMARY KEY is clustered with the data in InnoDB.
⚈  "INDEX(y_id, x_id)" -- The PRIMARY KEY makes it efficient to go one direction; this index makes the other direction efficient. No need to say UNIQUE; that would be extra effort on INSERTs.
⚈  In the secondary index, saying just INDEX(y_id) would work because it would implicit include x_id. But I would rather make it more obvious that I am hoping for a 'covering' index.

要有条件地插入新链接,请使用IODKU

请注意,如果此表中有AUTO_INCREMENT,IODKU会“烧掉”#34; ids很快。

相关问题