MySQL Select查询运行非常慢

时间:2019-02-20 11:39:12

标签: mysql

我有一个有效的MySQL查询,但速度很慢。我猜是由于连接的数量。

CREATE TABLE `categories` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `category` varchar(45) DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=latin1


CREATE TABLE `order_header` (
  `order_head_id` int(11) NOT NULL AUTO_INCREMENT,
  `status` varchar(45) DEFAULT NULL,
  `category` varchar(45) NOT NULL,
  `order_date` date DEFAULT NULL,
  `supplier_id` varchar(45) NOT NULL,
  `user` varchar(45) DEFAULT NULL,
  `sage_ref` varchar(45) DEFAULT NULL,
  `query_notes` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`order_head_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2249 DEFAULT CHARSET=latin1

CREATE TABLE `order_lines` (
  `order_lines_id` int(11) NOT NULL AUTO_INCREMENT,
  `order_head_id` int(11) DEFAULT NULL,
  `qty` int(11) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  `unit_price` decimal(65,2) DEFAULT NULL,
  `total_price` decimal(65,2) DEFAULT NULL,
  PRIMARY KEY (`order_lines_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3981 DEFAULT CHARSET=latin1

CREATE TABLE `suppliers` (
  `supp_id` int(11) NOT NULL AUTO_INCREMENT,
  `supplier` varchar(255) DEFAULT NULL,
  `status` varchar(225) DEFAULT NULL,
  PRIMARY KEY (`supp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=161 DEFAULT CHARSET=latin1

EXPLAIN查询的结果 enter image description here

SHOW CREATE TABLE结果

{{1}}

SQL版本5.6.30

我对MySQL的了解不是很好,并且想知道是否有人可以看到一种改进查询以使其运行更快的方法。

我们将不胜感激您的帮助。

非常感谢,

约翰

1 个答案:

答案 0 :(得分:0)

将第一个(左)联接包装到GROUP BY子查询中是有意义的。 GROUP BY和LIMIT将限制在以下两个联接中使用的行数:

SELECT 
    x.order_head_id,
    x.order_date,
    x.status,
    suppliers.supplier,
    categories.category,
    x.user,
    x.sage_ref,
    x.price
FROM (
    SELECT 
      order_header.supplier_id,
      order_header.category,
      order_header.order_head_id,
      order_header.order_date,
      order_header.status,
      order_header.user,
      order_header.sage_ref,
      SUM(order_lines.total_price) AS price
    FROM order_header
    LEFT JOIN order_lines ON order_header.order_head_id = order_lines.order_head_id
    WHERE order_header.status LIKE '%'
      AND order_header.order_head_id LIKE '%'
      AND order_header.user LIKE '%'
    GROUP BY order_header.order_head_id
    ORDER BY order_head_id DESC
    LIMIT 50
) x
LEFT JOIN suppliers  ON x.supplier_id = suppliers.supp_id
LEFT JOIN categories ON x.category    = categories.cat_id
ORDER BY order_head_id DESC