I am trying to implement a top-result search for a playlist. The tables are like so:
Playlist: id, title
Assignments: id, youtube_id, position
Videos: youtube_id, title
So joining them is simply: Playlist =(id)= Assignments =(youtube_id)= Videos
I want to find the first playlist on a title match (Titles are not unique) and match it to each of it’s videos, to bring back a list of videos in that playlist. I tried the following query:
SELECT *
FROM (
SELECT id, title, position, youtube_id
FROM playlists p
JOIN playlist_assignments pa
USING(id)
WHERE 1 and title = 'My Top Videos'
LIMIT 1
)d
JOIN videos v
USING (youtube_id)
ORDER BY position ASC
Unfortunately, the query will only return 1 row, the playlist matched with just the first video. How can I limit the subquery to just the top result, but still have a final result of a multiple row answer?
The issue with your query is that the sub-query is doing a
LIMIT 1, which means that though you retrieved a single playlist but then you also retrieved a singleyoutube_id. Then when did you ran a JOIN withvideoson that singleyoutube_id, it gives you a single record.The fix might be to SELECT only from
playliststable in the sub-query and move the JOIN forplaylist_assignmentsoutside together with thevideosjoin. Something like:My suggested query is:
Hope this helps. Let me know if it worked or if it didn’t.