0

I have 3 tables: restaurants, addresses and rates. I want to have a select statement to pick up all names of the restaurants, cities where the restaurants are and average rates of that restaurants. I have written something like this:

SELECT res.name as name,
       AVG(rate) as rate,
       ad.city as city
FROM restaurants res
JOIN rates r
    on res.id = r.restaurantid
JOIN addresses ad
    on res.addressid = ad.id
GROUP BY res.name, ad.city

It works fine as long as all restaurants have at least one rate, if not, the restaurant is not in the result. How can I improve this query to get all the restaurants with their cities and average rate of that restaurants and if there is no rate for the restaurant let's say assign rate 0.0.

1
  • 2
    Use LEFT JOIN rates r instead of JOIN rates r. Commented Dec 30, 2019 at 22:10

1 Answer 1

3

THis will do it: LEft join the rates table and when null replace with 0 the rate

SELECT res.name as name,
       AVG(coalesce(rate,0)) as rate,
       ad.city as city
FROM restaurants res
LEFT JOIN rates r
    on res.id = r.restaurantid
JOIN addresses ad
    on res.addressid = ad.id
GROUP BY res.name, ad.city
Sign up to request clarification or add additional context in comments.

2 Comments

nice catch GMB.
Probably you want COALESCE() around AVG(), not within (aggregate functions ignore NULLs).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.