MySQL加入查询GROUP BY

时间:2014-04-12 09:52:44

标签: mysql sql

我有2张桌子。 (酒店,地点)。

我想检索所有位置,并计算该位置的酒店数量。

现在我有以下查询:

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

查询工作正常,但问题是,它只给我一个或多个酒店的位置。我想显示所有位置(即使该位置没有酒店)。

3 个答案:

答案 0 :(得分:2)

您应该更改为左连接:

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

否则可能更容易理解:

select
  locations.*
  (select count(*) from hotels where hotels.location_id = locations.id) as no_of_hotels 
from
  locations
order by no_of_hotels desc

答案 1 :(得分: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

答案 2 :(得分:0)

尝试使用INNER JOIN

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