mysql - 优化 MYSQL 查询

标签 mysql optimization

我有一个旧版 PHP 应用程序(不使用任何框架) - 在某些地方它确实会变慢,某些查询需要 8-10 秒。

下面是这些缓慢查询之一的摘录,我可以看到我正在获取文件排序,这表明它运行缓慢的原因(或者至少我推测) - 任何人都可以建议如何优化我的查询以防止使用文件排序?该表大约有 600,000 行(因此相当大)

Schema added:
(MailList_Tags)
Field   Type    Null    Key Default Extra
MailListID  int(11)     PRI 0    
Tag varchar(60)     PRI      

(MailList)    
Field   Type    Null    Key Default Extra
MailListID  int(11)     PRI NULL    auto_increment
GroupID varchar(8)  YES     NULL     
HotelID varchar(8)  YES     NULL     
Title   varchar(20) YES     NULL     
FirstName   blob    YES     NULL     
LastName    blob    YES     NULL     
CompanyName varchar(200)    YES     NULL     
Address blob    YES     NULL     
Postcode    varchar(12) YES     NULL     
Country varchar(200)    YES     NULL     
Tel varchar(40) YES     NULL     
Fax varchar(40) YES     NULL     
Email   blob                 
md5digest   varchar(32)     UNI      
Sub1    int(1)      MUL 0    
Sub2    int(1)      MUL 0    
Sub3    int(1)      MUL 0    
OptInState  char(1)     MUL P    
UpdateDetailsState  char(1) YES     NULL     
Bounce  int(11)         0


EXPLAIN SELECT  `Tag` , COUNT( DISTINCT (
`MailList_Tags`.`MailListID`
) ) AS  `Count` 
FROM  `MailList` 
JOIN  `MailList_Tags` ON  `MailList`.`MailListID` =  `MailList_Tags`.`MailListID` 
WHERE HotelID =  'ca4b9ac9'
AND OptInState =  'V'
GROUP BY  `Tag`

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  MailList_Tags   index   MailListID  MailListID  64  NULL    962583  Using index; Using filesort
1   SIMPLE  MailList    eq_ref  PRIMARY,OptInState  PRIMARY 4   user_db.MailList_Tags.MailListID    1   Using where

最佳答案

您需要一些索引:

  • 在表 MailList_Tags 上,在 (Tag, MailListID) 上添加 UNIQUE 索引

  • 在表 MailList 上,在 (OptInState, HotelID, MailListID) 上添加索引。

然后尝试此查询(将 COUNT( DISTINCT MailList_Tags.MailListID ) 更改为 COUNT(*),应该产生相同的结果):

SELECT  Tag 
     ,  COUNT( * )
          AS  `Count` 
FROM  MailList 
  JOIN  MailList_Tags 
    ON  MailList.MailListID = MailList_Tags.MailListID 
WHERE  HotelID =  'ca4b9ac9'
  AND  OptInState =  'V'
GROUP BY  Tag

或者这个:

SELECT  Tag 
     ,  COUNT(*)
          AS  `Count` 
FROM  MailList 
WHERE  EXISTS 
       ( SELECT  *
         FROM  MailList_Tags 
         WHERE  MailList.MailListID = MailList_Tags.MailListID 
           AND  HotelID =  'ca4b9ac9'
           AND  OptInState =  'V'
       )
GROUP BY  Tag

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

相关文章:

mysql - MySQL 中的 Hibernate 和 Com_show_warnings == Com_select

mysql - 将 mySQL 从开发转移到生产

php - PHP : got nothing with printing the array 中的 SQL 查询

c++ - 网格中的高效方法

r - 使用 caret 包找到 GBM 的最佳参数

php - 来自数据库的 session 详细信息的用户名

php - 将 mysql TIME 从 24 HR 转换为 AM/PM 格式

optimization - 如何在 OpenShift 3.6 中获取有关最新成功部署 pod 的信息

python - 在 numba 中使用 numpy.vstack

c++ - 如何重载 std::swap()