簡體   English   中英

MySQL查詢優化避免文件排序

[英]MySql Query Optimization to avoid filesort

我希望有人幫助我優化並避免在以下查詢中進行文件排序。 附上其說明的屏幕截圖

SELECT DISTINCT(storages.id), 
     IF(admin_approve = 1 
           OR storage_free_auctions.user_id = 167 
           OR ISNULL(storage_free_auctions.user_id), 
        auction_date, NULL) AS auction_date1
FROM user_list_storage 
JOIN storages ON storages.id = user_list_storage.storage_id 
JOIN states ON states.id = storages.state 
LEFT JOIN storage_auctions ON storage_auctions.id = (
          SELECT storage_auctions.id FROM storage_auctions 
          LEFT JOIN storage_free_auctions 
          ON storage_free_auctions.storage_auctions_id=storage_auctions.id 
          WHERE storage_auctions.storage_id = storages.id 
          AND storage_auctions.status = 'Active' 
          AND (  ISNULL(storage_free_auctions.user_id) 
                 OR admin_approve = 1 
                 OR storage_free_auctions.user_id = 167) 
          AND CONCAT(auction_date,' ',start_time) >= CURDATE() 
          ORDER BY auction_date ASC LIMIT 1) 
LEFT JOIN storage_free_auctions 
     ON storage_free_auctions.storage_auctions_id=storage_auctions.id 
LEFT JOIN storage_auction_units 
     ON storage_auction_units.storage_auction_id = storage_auctions.id 
     AND storage_auction_units.status='Active' 
WHERE storages.storage_status = 'Active' 
AND user_list_storage.user_id = 167 
AND user_list_storage.user_list_id = 3 
AND (storage_free_auctions.user_id = 167 
     OR admin_approve = 1 
     OR ISNULL(storage_free_auctions.user_id) 
     OR user_list_storage.user_id = 167) 
GROUP BY storages.id 
order by auction_date1

解釋結果的第一行如下。

id: 1 Select_type: PRIMARY 表: user_list_storage 類型: ref 可能的 鍵: idx_user_list_id,idx_storage_id,idx_user_id 密鑰: idx_user_id key_len: 5 ref: const
行: 64
額外:在哪里使用; 使用臨時; 使用文件排序

更換

 LEFT JOIN storage_auctions 
        ON storage_auctions.id= (SELECT storage_auctions.id 
            FROM storage_auctions 
            LEFT JOIN storage_free_auctions 
                ON storage_free_auctions.storage_auctions_id = storage_auctions.id 
            WHERE storage_auctions.storage_id = storages.id 
              AND storage_auctions.status = 'Active' 
              AND (ISNULL(storage_free_auctions.user_id)
                    OR admin_approve = 1 
                    OR storage_free_auctions.user_id = 167) 
            AND CONCAT(auction_date,' ',start_time) >= CURDATE() ORDER BY auction_date ASC LIMIT 1) 

AND EXISTS (SELECT 1 
    FROM storage_auctions  
    WHERE storage_auctions.id = storages.id 
      AND CONCAT(auction_date,' ',start_time) >= CURDATE())

因為您在左聯接中的子句是多余的並且之前已經完成,所以您想要的是將來存在具有相同id的記錄,對嗎?

其余的聯接都可以。 它們都基於整數列,如果它們不是主鍵和runstats,請確保對所有這些id進行索引。

暫無
暫無

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

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