0

我在 Mysql 数据库中有三个表——国家、城市和酒店。他们的关系是:国家有很多城市,城市有很多酒店。

我希望能够选择给定特定国家/地区的所有酒店。id。我的 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

帮助?

4

2 回答 2

2

试着去掉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
于 2012-06-24T14:28:23.237 回答
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

额外的好处是您不需要外部连接:-)

于 2012-06-24T14:29:23.043 回答