gpt4 book ai didi

php - SQL 左连接只返回一行而不是多行

转载 作者:行者123 更新时间:2023-11-28 23:30:21 25 4
gpt4 key购买 nike

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

假设我正在寻找名为 Sibiu 的城市。这应该返回 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%'

最佳答案

添加 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, ....

关于php - SQL 左连接只返回一行而不是多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com