2013-08-02 59 views
0

我有以下表查詢優化調度

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 

這是最好的方式來查詢所有與'視角'字段的視頻?

我認爲必須有比這種方式更好,因爲我使用的是子查詢。

回答

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; 

但是,子查詢並不是什麼壞事。事實上,子查詢中的性能比這個版本更有可能。