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

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

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

4

1 回答 1

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;

但是,子查询并不是一件坏事。事实上,子查询的性能很可能比这个版本更好。

于 2013-08-02T22:22:15.633 回答