查询优化

时间:2013-08-02 22:17:42

标签: mysql join subquery

我有以下表格

chapters
    id
    title
videos
    id
    chapter_id
    video_url
viewed_videos
    id
    member_id
    video_id
    viewed_date

我现在正在使用以下查询。

select 
    c.id, 
    c.title, 
    c.duration, 
    c.visible, 
    v.id as vid, 
    v.title as video_title, 
    v.chapter_id, 
    v.duration as video_duration, 
    (select count(*) from viewed_videos where video_id = v.id and member_id=32) as viewed
from chapters as c
left join videos as v
on
c.id = v.chapter_id
where
c.tutorial_id = 19

这是使用“已查看”字段查询所有视频的最佳方式吗?

我认为必须有比这更好的方法,因为我使用子查询。

1 个答案:

答案 0 :(得分:2)

您不需要子查询。您可以在外层进行连接和聚合:

select c.id, c.title, c.duration, c.visible, v.id as vid, v.title as video_title, 
       v.chapter_id, v.duration as video_duration, v.video_token, count(*) as viewed
from chapters as c left join
     videos as v
     on c.id = v.chapter_id left join
     viewed_videos vv
     on vv.video_id = v.id and member_id=32
where c.tutorial_id = 19
group by c.id, v.id;

然而,子查询并不是一件坏事。实际上,子查询的性能很可能比使用此版本更好。