具有多个子查询的MySQL查询太慢。我该如何加快速度?

时间:2014-04-18 19:49:10

标签: mysql sql

我有一个MySQL查询,它完全符合我的要求,但它需要在110和110之间的任何地方。 130秒处理。问题是它与一个在查询后超过20秒的软件协同工作。

我有什么办法可以加快查询速度吗?我考虑将数据库移到另一台服务器上,但在我走这条路之前还有更优雅的选择吗?

-- 1 Give me a list of IDs & eBayItemIDs
-- 2 where it is flagged as bottom tier
-- 3 Where it has been checked less than 168 times
-- 4 Where it has not been checked in the last hour
-- 5 Or where it was never checked but appears on the master list.


-- 1 Give me a list of IDs & eBayItemIDs
SELECT `id`, eBayItemID 
FROM `eBayDD_Main` 
-- 2 where it is flagged as bottom tier
WHERE `isBottomTier`='0' 

-- 3 Where it has been checked less than 168 times
AND (`id` IN 
    (SELECT `mainid` 
    FROM `eBayDD_History` 
    GROUP BY `mainid`   
    HAVING COUNT(`mainID`) < 168) 
-- 4 Where it has not been checked in the last hour
AND id IN 
    (SELECT `mainID` 
    FROM `eBayDD_History` 
    GROUP BY `mainID` 
    HAVING ((TIME_TO_SEC(TIMEDIFF(NOW(), MAX(`dateCollected`)))/60)/60) > 1)) 
-- 5 Or where it was never checked but appears on the master list.
OR (`id` IN 
    (SELECT `id` 
    FROM `eBayDD_Main`) 
AND `id` NOT IN 
    (SELECT `mainID` 
    FROM `eBayDD_History`))

1 个答案:

答案 0 :(得分:0)

如果我理解正确的逻辑,你应该能够用这个替换这个逻辑:

select m.`id`, m.eBayItemID 
from `eBayDD_Main` m left outer join
      (select `mainid`, count(`mainID`) as cnt,
              TIME_TO_SEC(TIMEDIFF(NOW(), MAX(`dateCollected`)))/60)/60) as dc
       from `eBayDD_History` 
       group by `mainid`
      ) hm
      on m.mainid = hm.mainid
where m.`isBottomTier` = '0' and hm.cnt < 168 and hm.dc > 1 or
      hm.mainid is null;