2天前mysql查询很好,今天它超级慢

时间:2018-04-26 08:52:08

标签: mysql

好吧,正如标题所说,2天前查询运行正常,然后昨天突然间网站加载速度很慢。我跟踪了几个查询。一个我能够添加一个似乎有帮助的索引,但这个我无法弄清楚。我尝试在表格上进行修复和优化,但这并没有帮助。我不知道会发生什么变化,这会使它从不到一秒钟的查询变为20秒以上。任何帮助将不胜感激。

SELECT city 
FROM listings LEFT JOIN agencies 
ON listings.agencyid_fk = agencies.agencyid 
WHERE listingstatus IN (1,3) AND appid_fk = 101 AND active = 1 
      AND auction IS NULL AND agencies.multilist = 1 
      AND notagency IS NULL 
GROUP BY city 
ORDER BY city;

我不确定如何导出解释查询结果以使其在此处可读,因此我只是将其放在代码段中。单击运行以在html表中查看它。

id select_type table    type   possible_keys          key       key_len ref                       rows  Extra
 1 SIMPLE      listings ref    appid_fk,listingstatus appid_fk        2 const                     21699 Using where; Using temporary; Using filesort
 1 SIMPLE      agencies eq_ref PRIMARY,active         PRIMARY         2 mls2.listings.agencyid_fk     1 Using where

以下是表格......

列表表:

CREATE TABLE mls2.listings (
   listingid INT(11) AUTO_INCREMENT NOT NULL,
   appid_fk SMALLINT(3) NOT NULL DEFAULT '0',
   agencyid_fk SMALLINT(3) NOT NULL DEFAULT '0',
   listingstatus SMALLINT(3),
   city VARCHAR(30) CHARACTER SET latin1 COLLATE latin1_swedish_ci,
   multilist TINYINT(1),
   auction TINYINT(1),
   PRIMARY KEY (listingid)
) ENGINE = myisam ROW_FORMAT = DEFAULT CHARACTER SET latin1;

代理商表:

CREATE TABLE mls2.agenciesx (
   agencyid SMALLINT(6) AUTO_INCREMENT NOT NULL,
   multilist TINYINT(4) DEFAULT '0',
   notagency TINYINT(1),
   active TINYINT(1),
  PRIMARY KEY (agencyid)
) ENGINE = myisam ROW_FORMAT = DEFAULT CHARACTER SET latin1;

1 个答案:

答案 0 :(得分:0)

一旦您接受了上述评论,请尝试将以下索引添加到您的表格中......

INDEX(city,listingstatus,appid_fk,auction)
INDEX(active,multilist,notagency)

在这两种情况下,列在索引中排列的顺序可能有所不同,所以尽量使用这些,尽管代理表中的行数很少,但这一行并不重要。

接下来,摆脱GROUP BY子句,并按如下方式编写查询。

SELECT DISTINCT l.city 
           FROM listings l
           JOIN agencies a
             ON a.agencyid = l.agencyid_fk 
          WHERE l.listingstatus IN (1,3) 
            AND l.appid_fk = 101 
            AND a.active = 1 
            AND l.auction IS NULL 
            AND a.multilist = 1 
            AND a.notagency IS NULL 
          ORDER 
             BY city;

注意:虽然与此特定问题无关,但您的原始问题显示此架构极度需要规范化。