繁体   English   中英

Mysql查询工作很慢如何优化查询?

[英]Mysql query working very slow How can optimize query?

查询:

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上的数据库架构。

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

我有1500多行,执行几乎要花5秒钟的时间。如何优化此查询,以便此查询花费不到1秒钟的时间。

几个多对多表中缺少合适的索引是一个严重的性能问题。 遵循中的建议

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将非常迅速地“烧录” ID。

暂无
暂无

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

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