mysql查询工作很慢怎么能优化查询?

k7fdbhmy  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(400)

查询:

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`

如果您想访问schema。请访问sqlfiddle上的db schema。
http://sqlfiddle.com/#!9/c1b1e0/1号机组
我有1500多行,执行它几乎需要5秒,如何优化这个查询,使这个查询不到1秒。

kmb7vmvb

kmb7vmvb1#

在多对多表中缺少合适的索引是一个重要的性能问题。遵循中的建议
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。

相关问题