簡體   English   中英

帶有多個子查詢的MySQL查詢太慢。 如何加快速度?

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

我有一個MySQL查詢,它完全可以執行我想要的操作,但是需要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`))

如果我正確理解該邏輯,則應該可以用以下代碼替換此邏輯:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM