加快MySQL查询速度

时间:2014-10-26 22:02:11

标签: mysql sql performance

我需要帮助加快MySQL查询的运行速度非常慢。它需要超过35秒才能返回900行。

有没有人有想法如何加快这个问题的速度?

非常感谢提前

select products.*, 
p.price as lowest_price, 
products_images.thumbnail 
from products 
    inner join products_categories on products_categories.product_id = products.id 
    inner join products_colours on products_colours.product_id = products.id 
    inner join products_quantity_pricing on products_quantity_pricing.product_id = products.id 
    left join ( select min(price) as price, product_id from products_quantity_pricing group by products_quantity_pricing.product_id ) as p on p.product_id = products.id 
    inner join products_images on products_images.product_id = products.id 
where products.id > 0 group by products.id 
order by products.product_name    

以下是所涉及表格的设置:

CREATE TABLE IF NOT EXISTS `products_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` smallint(5) unsigned zerofill NOT NULL,
  `category` int(11) NOT NULL,
  `sub_category` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1016 ;


CREATE TABLE IF NOT EXISTS `products` (
   `product_prefix` varchar(10) NOT NULL,
   `id` smallint(5) unsigned zerofill NOT NULL AUTO_INCREMENT,
  `supplier_id` int(11) NOT NULL,
  `product_code` varchar(50) NOT NULL,
  `supplier_product_code` mediumtext NOT NULL,
  `product_name` varchar(200) NOT NULL,
  `product_description` text NOT NULL,
  `print_area` varchar(100) DEFAULT NULL,
  `print_position` varchar(100) DEFAULT NULL,
  `dimensions` varchar(100) DEFAULT NULL,
  `origination` tinytext,
  `unit_cost` decimal(9,2) NOT NULL,
  `updated` datetime NOT NULL,
  `url` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `product_code` (`product_code`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=901 ;


CREATE TABLE IF NOT EXISTS `products_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` smallint(5) unsigned zerofill NOT NULL,
  `fullsize` varchar(255) NOT NULL,
  `midsize` varchar(255) NOT NULL,
  `thumbnail` varchar(255) NOT NULL,
  `updated` datetime NOT NULL,
  `colour_tag` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2402 ;


CREATE TABLE IF NOT EXISTS `products_colours` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` smallint(5) unsigned zerofill NOT NULL,
  `colour` varchar(100) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `product_id` (`product_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2546 ;


CREATE TABLE IF NOT EXISTS `products_quantity_pricing` (
  `product_id` smallint(5) unsigned zerofill NOT NULL,
  `quantity` smallint(6) NOT NULL,
  `price` decimal(9,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:3)

在所有表格的product_id列上添加indexes

products_quantity_pricing中,(product_id, price)上的composite index也会加快查找每种产品的最低价格。如果创建此复合索引,则无需在product_id上创建单独的索引;复合索引的前缀也可以作为自己的索引。