简体   繁体   中英

MySQL query with multiple subqueries is too slow. How do I speed it up?

I have a MySQL query which does exactly what I want, but it takes anywhere between 110 & 130 seconds to process. The problem is that it works in tandem with a software that times out 20 seconds after making the query.

Is there anything I can do to speed up the query? I'm considering moving the db over to another server, but are there any more elegant options before I go that route?

-- 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`))

If I understand the logic correctly, you should be able to replace this logic with this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM