MySQL - 如何优化我的查询

标签 mysql optimization

我在进行良好的 MySQL 查询方面非常糟糕。我创建了这个:

SELECT SQL_CALC_FOUND_ROWS
  `products_stock`.`products_id`,
  `products_stock`.`products_stock_attributes`,
  `products_stock`.`products_stock_quantity`,
  `products`.`manufacturers_id`,
  `products_description`.`products_name`
FROM `products_stock` 
  LEFT JOIN  `products`
    ON  `products_stock`.`products_id` = `products`.`products_id` 
  LEFT JOIN  `products_description`
    ON  `products_stock`.`products_id` = `products_description`.`products_id` 
  LEFT JOIN  `products_to_categories`
    ON `products_stock`.`products_id` = `products_to_categories`.`products_id` 
WHERE `products_stock`.`products_stock_quantity` >=3
  AND `products`.`products_status` = 1
  AND ISNULL(`products`.`products_image`) = false
  AND `products`.`products_image` != ""
  AND EXISTS(
   select * from `allegro`
   where `products_stock`.`products_id` = `allegro`.`product_id` 
     and `allegro`.`attributes` =  `products_stock`.`products_stock_attributes`
  ) = false

products 表有大约 17k 行, allegro 表有大约 3k 行。

查询思路是select all products, where stock_quanity > 3, where is photo, where is no product id in allegro table.

现在查询大约需要 10 秒。我不知道如何优化它。

@已解决

我已将索引添加到 allegro.product_id 和 allegro.attributes,现在查询时间不到一半。感谢大家的帮助

最佳答案

去掉 EXISTS ( SELECT … ) = FALSE 东西。

将其转化为以下内容:

LEFT JOIN allegro
          ON products_stock.products_id = allegro.product_id
         AND allegro.attributes = products_stock.products_stock_attributes
…
WHERE allegro.product_id IS NULL

参见 Rewriting Subqueries as Joins MySQL 文档中的章节。

进一步的建议:

  • 不要加入您不使用的表,例如 products_to_categories
  • ISNULL(…) = FALSE 写成 … IS NOT NULL

关于MySQL - 如何优化我的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11429268/

相关文章:

image-processing - 将大图像时间发送到 GPU

javascript - 如何使用ajax将javascript变量中的值放入php变量中

php - 拉维尔 4 : custom login and check password

php - 添加到 PHP 生成的表的超链接

python - 如何有效地将整数提升为小数幂?

c - 海湾合作委员会优化?

mysql - 删除 mysql 表中列的重复第二个条目

使用插入值时出现 MySQL 存储过程语法错误

python - 如何优化Python pandas中的数据透视表代码

algorithm - 我可以使用什么算法来确定半圆内的点?