最低,MAx SQL查询优化

时间:2018-07-28 15:04:26

标签: mysql sql

我有以下查询,我确实需要帮助对其进行优化:

Float64

这些表是:

SELECT min(p.price) as min_price, max(p.price) as max_price
FROM product p
INNER JOIN product_category pc
    ON p.id_product = pc.id_product AND
       p.id_project = 1 AND
       pc.id_category = 2 AND
       p.active = 1 

有product_categories表:

CREATE TABLE `product` (
  `id_product` bigint(10) UNSIGNED NOT NULL,
  `id_project` int(11) NOT NULL,
  `reference` varchar(50) NOT NULL,
  `reference_internal` varchar(125) NOT NULL,
  `sku` varchar(50) NOT NULL,
  `price` float(12,2) NOT NULL,
  `old_price` float NOT NULL,
  `reduction_amount` float NOT NULL,
  `reduction_percent` float NOT NULL,
  `is_reduced` int(1) NOT NULL,
  `id_manufacturer` int(10) NOT NULL,
  `id_supplier` int(10) NOT NULL,
  `is_new` int(1) NOT NULL,
  `popularity` int(1) NOT NULL,
  `quantity` int(1) NOT NULL,
  `active` int(1) NOT NULL,
  `date_add` datetime NOT NULL,
  `date_upd` datetime NOT NULL,
  `id_category` int(11) NOT NULL,
  `indexed` int(1) NOT NULL,
  `id_color` int(13) NOT NULL,
  `rating` int(1) NOT NULL,
  `rating_count` int(11) NOT NULL,
  `viewed` int(5) NOT NULL,
  `a_id_product` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `product`
  ADD PRIMARY KEY (`id_product`),
  ADD KEY `id_product` (`id_product`),
  ADD KEY `reference` (`reference`),
  ADD KEY `reference_internal` (`reference_internal`),
  ADD KEY `sku` (`sku`),
  ADD KEY `reduction_amount` (`reduction_amount`),
  ADD KEY `reduction_percent` (`reduction_percent`),
  ADD KEY `is_reduced` (`is_reduced`),
  ADD KEY `id_manufacturer` (`id_manufacturer`),
  ADD KEY `id_supplier` (`id_supplier`),
  ADD KEY `is_new` (`is_new`),
  ADD KEY `popularity` (`popularity`),
  ADD KEY `date_add` (`date_add`),
  ADD KEY `date_upd` (`date_upd`),
  ADD KEY `id_category` (`id_category`),
  ADD KEY `indexed` (`indexed`),
  ADD KEY `id_color` (`id_color`),
  ADD KEY `price` (`price`),
  ADD KEY `rating` (`rating`),
  ADD KEY `a_id_product` (`a_id_product`),
  ADD KEY `t7` (`price`,`id_product`,`id_project`,`active`) USING BTREE;
-- AUTO_INCREMENT for dumped tables
-- AUTO_INCREMENT for table `product`
ALTER TABLE `product`
  MODIFY `id_product` bigint(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;

解释性说明https://snag.gy/8ClFnh.jpg

enter image description here 我有45个MS执行时间,但是数据库不是很大,我大约有20.000个产品,但是当它投入使用时,我将拥有数百万个产品,而对于这种数量的产品,0.0550秒的执行时间似乎很长,任何人都可以帮助进行优化建议?

我有mysql 5.7。

1 个答案:

答案 0 :(得分:0)

如果您选择的行数很少(占总数的0.5%或更少),则您的查询应该非常容易优化。

下面的索引应该有帮助:

create index ix1_product on product (id_project, active, price);

create index ix2_procat on product_category (id_product, id_category);