Reputation: 22565
I have the following tables
chapters
id
title
videos
id
chapter_id
video_url
viewed_videos
id
member_id
video_id
viewed_date
I'm using the following query now.
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
Is this the best way to query all the videos with 'viewed' field?
I think there must be a better than this way since i'm using a subquery.
Upvotes: 0
Views: 28
Reputation: 1269773
You don't need the subquery. You can do the join and aggregation at the outer level:
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;
However, the subquery is not such a bad thing. In fact, it is quite possible that the performance is better with the subquery than with this version.
Upvotes: 2