0

I have 2 tables. (hotels, locations).

I want to retrieve all the locations with a count of number of Hotels in that location.

Right now I have the following query:

SELECT locations.*, 
COUNT(*) as no_of_hotels 
FROM locations RIGHT JOIN hotels ON hotels.location_id = locations.id 
GROUP BY locations.id 
ORDER BY no_of_hotels DESC

The query works fine, but the problem is, It gives me only the locations with 1 or more hotels. I want to show all the locations (even though the location has no hotels).

3 Answers 3

2

You should change to left join:

SELECT locations.*, 
       COUNT(distinct hotels.id) as no_of_hotels 
       FROM locations 
       LEFT JOIN hotels ON hotels.location_id = locations.id 
       GROUP BY locations.id 
       ORDER BY no_of_hotels DESC

Otherwise probably this is easier to understand:

select
  locations.*
  (select count(*) from hotels where hotels.location_id = locations.id) as no_of_hotels 
from
  locations
order by no_of_hotels desc
Sign up to request clarification or add additional context in comments.

2 Comments

Left join works, but it gives the value 1 for no_of_hotels, even though there aren't any hotels. But the second solution works well.
I modified a bit. Can you try it? (And probably the second one would give the correct result as well.
1
SELECT locations.*, (SELECT count(*) FROM hotels WHERE hotels.location_id = locations.id) AS no_of_hotels FROM locations ORDER BY no_of_hotels DESC

Comments

0

Try with INNER JOIN like this

SELECT locations.*, 
COUNT(*) as no_of_hotels 
FROM locations INNER JOIN hotels ON hotels.location_id = locations.id 
GROUP BY locations.id 
ORDER BY no_of_hotels DESC

Comments

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.