我有以下表格
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这是查询所有带有“查看”字段的视频的最佳方式吗?
我认为肯定有比这更好的方式,因为我使用的是子查询。
发布于 2013-08-02 22:22:15
您不需要子查询。您可以在外部级别进行连接和聚合:
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;但是,子查询并不是一件坏事。事实上,子查询的性能很可能比这个版本更好。
https://stackoverflow.com/questions/18026925
复制相似问题