草庐IT

MySQL 慢大查询

coder 2023-10-03 原文

我有一个我想优化的大型查询,我已经优化了它,但它有时仍然很慢 (>1s):

select count(DISTINCT if(ps15.specification in ('All Season'),p.products_id,NULL)) as count1 ,count(DISTINCT if(ps15.specification in ('Winter'),p.products_id,NULL)) as count2 ,count(DISTINCT if(ps15.specification in ('Zomer'),p.products_id,NULL)) as count3 ,count(DISTINCT if(ps15.specification in ('Winter 2012'),p.products_id,NULL)) as count4 ,count(DISTINCT if(ps15.specification in ('Zomer 2013'),p.products_id,NULL)) as count5 ,count(DISTINCT if(ps15.specification in ('Winter 2013'),p.products_id,NULL)) as count6 ,count(DISTINCT if(ps15.specification in ('Zomer 2014'),p.products_id,NULL)) as count7
from (products p)
inner join (products_to_categories p2c)
  on (p.products_id = p2c.products_id)
inner join (products_attributes pa)
  on (p.products_id = pa.products_id)
inner join (products_options_values pv)
  on (pa.options_values_id = pv.products_options_values_id)
inner join (products_stock ps)
  on (p.products_id=ps.products_id 
    and pv.products_options_values_id = ps.products_options_values_id2 
    and ps.products_stock_quantity>0)
INNER JOIN products_specifications ps15 
  ON p.products_id = ps15.products_id  
    AND ps15.specifications_id = '15'
    AND ps15.language_id = '1'
INNER JOIN products_specifications ps10 
  ON p.products_id = ps10.products_id  
    AND ps10.specifications_id = '10' 
    AND ps10.language_id = '1' 
where p.products_status = '1'
  and p2c.categories_id in (72,1,23,100,74,24,33,34,35,77,110,25,45,44,40,41,42,85,76,78,83,102,107,111,119,50,52,81,105,108,112,86,88,87,98,89,90,91,96,79,2,54,60,82,109,115,118,53,58,104,55,101,75,56,64,66,67,68,69,70,71,84,103,114,120,80,92,99,93,94,95,97,106,121)  
  AND ps10.specification in ('Meisje')  
  and products_options_values_name in ( 62,"3M/60cm","56-62","0-4 mnd","3m","0-3m","3-6m","3M","62/68","0-6m","50-62" , 68,"6M/67cm","9M/70cm","4-8 mnd","6m","3-6m","6M","62/68","0-6m" , 74,"4-8 mnd","8-12 mnd","6m","9m","6-9m","6M","9M","74/80","6-12m" );

输出是:

+--------+--------+--------+--------+--------+--------+--------+
| count1 | count2 | count3 | count4 | count5 | count6 | count7 |
+--------+--------+--------+--------+--------+--------+--------+
|      1 |    289 |    193 |     49 |    192 |    240 |      0 |
+--------+--------+--------+--------+--------+--------+--------+

解释 mysql 输出:

+----+-------------+-------+-------+-------------------------------------------+-------------------------------------+---------+---------------------------------------+------+--------------------------+
| id | select_type | table | type  | possible_keys                             | key                                 | key_len | ref                                   | rows | Extra                    |
+----+-------------+-------+-------+-------------------------------------------+-------------------------------------+---------+---------------------------------------+------+--------------------------+
|  1 | SIMPLE      | p     | index | PRIMARY,products_id                       | products_id                         | 5       | NULL                                  | 4539 | Using where; Using index |
|  1 | SIMPLE      | p2c   | ref   | PRIMARY                                   | PRIMARY                             | 4       | kikleding.p.products_id               |    1 | Using where; Using index |
|  1 | SIMPLE      | ps15  | ref   | products_id                               | products_id                         | 12      | kikleding.p2c.products_id,const,const |    1 | Using where              |
|  1 | SIMPLE      | ps10  | ref   | products_id                               | products_id                         | 12      | kikleding.p.products_id,const,const   |    1 | Using where              |
|  1 | SIMPLE      | pa    | ref   | idx_products_attributes_products_id       | idx_products_attributes_products_id | 4       | kikleding.p.products_id               |    6 |                          |
|  1 | SIMPLE      | pv    | ref   | PRIMARY                                   | PRIMARY                             | 4       | kikleding.pa.options_values_id        |    2 | Using where              |
|  1 | SIMPLE      | ps    | ref   | idx_products_stock_attributes,products_id | idx_products_stock_attributes       | 4       | kikleding.ps15.products_id            |    6 | Using where              |
+----+-------------+-------+-------+-------------------------------------------+-------------------------------------+---------+---------------------------------------+------+--------------------------+

我已尝试对大多数表进行索引,但 ref 在解释的第一行中仍然给出 NULL。

现在输出7列,有时我需要输出50列。

有什么建议吗?

最佳答案

ref = NULL 仅表示 p 表(即 product)中的行未与其他行连接。这些行是您查询中最先选择的行,其他表中的行将再次与它们连接。我总是希望 EXPLAIN 的第一行显示 ref = NULL

基本上,您的执行计划说:

  1. products 中提取符合 WHERE 条件的行
  2. 然后从 products.products_id 字段中的 (1) 中提取行 products_to_categories 匹配行
  3. 所有表依此类推

建议的附加索引:

  • 表格(列)
  • 产品(product_id,products_status)
  • 产品规范(产品编号、规范、语言编号、规范编号)
  • products_to_categories(products_id, categories_id)

第一个应该很有帮助,我对其他两个的期望不高。

我认为问题出在您的许多 COUNT(IF()) 上。这是骇人听闻的,并且引擎并未真正针对此类查询进行优化。相反,您必须以返回这样的结果集为目标:


+---------------+-------+
| specification | count |
+---------------+-------+
| All Season    |     1 |
+---------------+-------+
| Winter        |   289 |
+---------------+-------+
| ...           |   ... |
+---------------+-------+

Your query would look like this:

SELECT
    specification,
    COUNT(*)
FROM products
JOIN ... -- your current JOIN list
GROUP BY specification -- this is the important bit

...并且应该几乎是即时的,即使没有额外的索引(或者可能在 products_specifications(products_id, specification) 上)

关于MySQL 慢大查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448393/

有关MySQL 慢大查询的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  3. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  4. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  5. ruby-on-rails - 无法安装 mysql2 0.3.14 gem - 2

    我看到其他人也遇到过类似的问题,但没有一个解决方案对我有用。0.3.14gem与其他gem文件一起存在。我已经完全按照此处指示完成了所有操作:https://github.com/brianmario/mysql2.我仍然得到以下信息。我不知道为什么安装程序指示它找不到include目录,因为我已经检查过它存在。thread.h文件存在,但不在ruby​​目录中。相反,它在这里:C:\RailsInstaller\DevKit\lib\perl5\5.8\msys\CORE\我正在运行Windows7并尝试在Aptana3中构建我的Rails项目。我的Ruby是1.9.3。$gemin

  6. ruby-on-rails - solr 清理查询 - 2

    我在Rails上使用带有ruby​​的solr。一切正常,我只需要知道是否有任何现有代码来清理用户输入,比如以?开头的查询。或* 最佳答案 我不知道执行此操作的任何代码,但理论上可以通过查看parsingcodeinLucene来完成并搜索thrownewParseException(只有16个匹配!)。在实践中,我认为您最好只捕获代码中的任何solr异常并显示“无效查询”消息或类似信息。编辑:这里有几个“sanitizer”:http://pivotallabs.com/users/zach/blog/articles/937-s

  7. ruby-on-rails - Rails 3 在一个查询中包含多个表 - 2

    我正在为锦标赛开发一个Rails应用程序。我在这个查询中使用了三个模型:classPlayertruehas_and_belongs_to_many:tournamentsclassTournament:destroyclassPlayerMatch"Player",:foreign_key=>"player_one"belongs_to:player_two,:class_name=>"Player",:foreign_key=>"player_two"在tournaments_controller的显示操作中,我调用以下查询:Tournament.where(:id=>params

  8. ruby-on-rails - Sunspot:如何对具有不同值的多个字段进行全文查询? - 2

    我想用sunspot重现以下原始solr查询q=exact_term_text:fooORterm_textv:foo*ORalternate_text:bar*但我无法通过标准的太阳黑子界面理解这是否可能以及如何实现,因为看起来:fulltext方法似乎不接受多个文本/搜索字段参数我不知道将什么参数作为第一个参数传递给fulltext,就好像我通过了"foo"或"bar"结果不匹配如果我传递一个空参数,我得到一个q=*:*范围过滤器(例如with(:term).starting_with('foo*')(顾名思义)作为过滤器查询应用,因此不参与评分。似乎可以手动编写字符串(或者可能使

  9. ruby - 如何使用 ruby​​ mysql2 执行事务 - 2

    我已经开始使用mysql2gem。我试图弄清楚一些基本的事情——其中之一是如何明确地执行事务(对于批处理操作,比如多个INSERT/UPDATE查询)。在旧的ruby-mysql中,这是我的方法:client=Mysql.real_connect(...)inserts=["INSERTINTO...","UPDATE..WHEREid=..",#etc]client.autocommit(false)inserts.eachdo|ins|beginclient.query(ins)rescue#handleerrorsorabortentirelyendendclient.commi

  10. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

随机推荐