mercredi 21 octobre 2015

Return all rows from a table and information from another for specific row

I'm trying to make a simple video rate system for a website using two tables, videos and ratings. Basically, there's a video record on the "videos" table, and then 1 or n ratings for that video id inside the "ratings" table. I can select a single video record and add a column based on the average of all the ratings for that video doing:

SELECT v.*, avg(r.rate) FROM videos v
LEFT JOIN ratings r
ON v.id = r.video_id
WHERE v.id = 100;

This returns:

id     |   name      |  file     |   rate
------------------------------------------
100    |   Testvideo | test.avi  |  4.4286 

There are 7 rows for that id inside "ratings" ranging from integers 3 to 5, so the average is working as expected, if the specific video doesn't have a rating it'd throw null for the rate column but everything else shows up. So, I have the method for single ID covered up, but I can't figure out what the query would be if I want to return the whole video list in the same format

id   |   name      |  file        |   rate
------------------------------------------
1    |   test1     | test1.avi    |  5 
2    |   super2    | conan.avi    |  null
3    |   mega3     | wedding.avi  |  2.1149

I tried a lot of things, but they all returned either a single row (which I assume is because of the avg function) or duplicated rows.

Thanks.

Aucun commentaire:

Enregistrer un commentaire