SQL left join只返回一行而不是多行

时间:2016-05-29 18:16:12

标签: php mysql

我有两个表,一个是城市(id和城市名称),另一个是城市图片(city_id等)。

假设我正在寻找名为锡比乌的城市。这应该返回3个结果,因为表中有更多的城市(Miercurea Sibiului,Sibiu,Poiana Sibiului),但它只返回一个。

此外,作为备注,timeline_elements还没有该城市的任何图片。

SELECT cities_countries.*, COUNT(timeline_elements.city_id) as number_of_photos 
FROM cities_countries   
LEFT JOIN timeline_elements on (cities_countries.id = timeline_elements.city_id)
WHERE cities_countries.name LIKE '%Sibiu%'

1 个答案:

答案 0 :(得分:1)

添加GROUP BY并明确提及cities_countries表的所有列名称。我认为这些是cities_countries表中的列。 id, city_id, city_name

还为每个表设置别名,以提高可读性。

SELECT C.id, C.city_id, C.city_name, ....
       , COUNT(T.city_id) as number_of_photos 
FROM cities_countries C  
LEFT JOIN timeline_elements T ON C.id = T.city_id
WHERE C.name LIKE '%Sibiu%'
GROUP BY C.id, C.city_id, C.city_name, ....