我在Mysql数据库中有三个表 - 国家,城市和酒店。他们的关系是:国家有很多城市和城市都有很多酒店。
我希望能够选择给定某些国家/地区的所有酒店。我在SQL方面很弱。我想出的连接语句如下,总是返回0行。
SELECT
countries.name as country,
cities.name as city,
hotels.name as hotel
FROM
countries
left join cities
on countries.id = cities.country_id
left join hotels
on cities.id = hotels.city_id
WHERE
countries.id = @id
帮助?
答案 0 :(得分:2)
尝试离开 off where子句并查看实际所拥有的记录。也许您使用的具体ID不是已知的国家/地区ID。
另外,仅仅是严格的格式/样式问题,恕我直言,这是更好的:
SELECT
countries.name as country,
cities.name as city,
hotels.name as hotel
FROM countries
left join cities on cities.country_id = countries.id
left join hotels on hotels.city_id = cities.id
WHERE countries.id = @id
答案 1 :(得分:1)
我的经验法则是始终使用我想要的实际表格来启动我的FROM子句。
SELECT
countries.name as country,
cities.name as city,
hotels.name as hotel
FROM
hotels JOIN cities ON cities.id = hotels.city_id
join countries on countries.id = cities.country_id
WHERE
countries.id = @id
额外的好处是你不需要外连接: - )