mysql group by using filesort優化


  1. 原join 連接語句
SELECT 
    SUM(video_flowers.number) AS num,
    video_flowers.flower_id,
    flowers.title,
    flowers.image
FROM
    `video_flowers`
        JOIN
    `flowers` ON `video_flowers`.`flower_id` = `flowers`.`id`
        JOIN
    `video_posts` ON `video_flowers`.`video_post_id` = `video_posts`.`id`
WHERE
    `video_posts`.`user_id` = 36
GROUP BY `video_flowers`.`flower_id`

可以優化成

SELECT 
    vf.num, flowers.title, flowers.image
FROM
    `flowers`
        
        join
    (SELECT 
        SUM(video_flowers.number) AS num, video_flowers.flower_id, video_flowers.video_post_id
    FROM
        video_flowers 
    GROUP BY `video_flowers`.`flower_id`) AS vf ON `vf`.`flower_id` = `flowers`.`id`
    join `video_posts` on `video_posts`.`id` = vf.`video_post_id`
    where video_posts.user_id = 36;

這樣就沒有using filesort 和using temporary


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM