优化join / union sql?

时间:2011-08-14 06:49:13

标签: mysql select union

我有以下运行得相当好的SQL查询,但是在返回60,000-70,000行的类别时它似乎停滞不前。我想知道如何优化这一点,无论是服务器端还是代码本身,以尽可能快地运行。虽然它通常会被缓存,但是这个语句将在每天有100,000次点击的网络上使用,我需要它平滑或至少完成查询执行。

SELECT * FROM
( 
    (
        SELECT DISTINCT
            vc.category_id, t.tube_title, v.*, COUNT(vc.video_id) AS total_clicks
        FROM video_click vc
        JOIN tube t ON vc.tube_id = t.tube_id
        JOIN video v ON v.video_id = vc.video_id
        WHERE
                vc.time >= 1313153417
            AND
                vc.category_id = 123
        GROUP BY vc.video_id
    )
    UNION
    (
        SELECT DISTINCT
            vd.category_id, t.tube_title, v.*, COUNT(NULL) as total_clicks
        FROM
            video_data vd
        JOIN tube t ON vd.tube_id = t.tube_id
        JOIN video v ON v.video_id = vd.video_id
        WHERE
            vd.category_id = 123
        GROUP BY vd.video_id
    )
) AS final_video
GROUP BY final_video.video_id
ORDER BY total_clicks DESC

我感谢任何提示或帮助以允许上述内容在更大的数据库选择上运行。 谢谢!

1 个答案:

答案 0 :(得分:1)

看起来您只与video_data表联合,以确保您获得没有点击的视频的计数。使用左连接可以更容易地实现这一点。

SELECT
    vd.category_id, t.tube_title, v.*, COUNT(vc.video_id) AS total_clicks
FROM video_data vd
    LEFT JOIN video_click vc ON vc.video_id = vd.video_id AND vc.time > 1313153417
    JOIN tube t ON vd.tube_id = t.tube_id
    JOIN video v ON vd.video_id = v.video_id
WHERE
    vd.category_id = 123
GROUP BY v.video_id
ORDER BY COUNT(vc.video_id) desc

这应该比您之前的查询运行得更快,但请确保检查它是否返回了您想要的结果。