Skip to content
Advertisement

How to count favorites and all data of an other table with JOIN

I try to select the favorites for each wines in my database and all data from wines but with the group by obligation, I can’t have data for wines which don’t have a favorite_score, so do you know how to do please.

This is my SQL request for instance and now this my DB diagram : enter image description here

So, I want all data for each wine and favorite_score too for each one or 0 if there is no data corresponds on wines.id = favorites.wine_id Sorry for my English, I’m French

Advertisement

Answer

I wouldn’t do a sum, because that will sum all the wine_ids and not the number of wine_ids in the table favorites.

for example, you have wine_id = {50, 100,123} and a SUM(wine_id) would be 273, but I assume that what you want is 3 instead. So based on that, the query I would do is as follows

Let me know if you have any questions. Also, don’t forget that for the count to work you need to add all the other fields in the group by, so I would advice you to only take the necessary fields.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement