0

I'm developing a rating system as part of a web application. I'm trying to run a query which returns the average for each entry in the data set. Below is the query I've started with:

SELECT hotel_id, 
hotel_logo, 
hotel_name, 
hotel_website, 
hotel_facebook, 
hotel_rating, 
hotel_verified,
hotel_location,
hotel_founded_in
FROM hotels

This works as expected and returns all the hotels & specified data fields.

To try and get the average of each set of reviews under a hotel I've used to following:

SELECT hotels.hotel_id, 
AVG(review_total_rating),
hotel_logo, 
hotel_name, 
hotel_website, 
hotel_facebook, 
hotel_rating, 
hotel_verified,
hotel_location,
hotel_founded_in
FROM hotels
INNER JOIN reviews
ON hotels.hotel_id = reviews.hotel_id

This query is returning the correct values but ONLY for a single row, I am also getting a MySQL warning saying there is no unique identifier.

How can I adjust the above query to bring back the specified data for every field in the table?

Any help appreciated.

2
  • 1
    you have to do GROUP BY hotel_id,hotel_logo,hotel_name,hotel_website,hotel_rating... Commented Jun 3, 2019 at 19:27
  • 1
    To point out what others didn't, if you were getting the correct average, it was only coincidentally. Without the GROUP BY, you were getting the average of all joined records.... and an effectively random selection of values for the non-aggregated, non-grouped fields. Commented Jun 3, 2019 at 20:07

1 Answer 1

1

Just add: GROUP BY hotels.hotel_id assuming it is the PK.

Sign up to request clarification or add additional context in comments.

2 Comments

I have just done this, and it works mostly. The only problem is that if an entry has no value for AVG(review_total_rating) in the review table the whole entry is ignored. Is there a way for me to return the rest of the data for the row rather than ignoring the whole entry if the total review field is empty?
Yes, just use LEFT JOIN instead of INNER JOIN.

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.