如何在多个表层次结构级别上执行mysql join语句?

时间:2010-09-17 01:42:06

标签: mysql join

假设我有以下表格:

House:
id
name
cityID

其中cityID指的是表格城市的id字段

City:
id
name
stateID

其中stateID指的是表状态的id字段

State:
id
name
countryID

其中countryID指的是表国家/地区的ID字段:

Country:
id
name

如何使用mysql join语句,以便使用此多级位置引用层次结构获取特定国家/地区内的房屋?

1 个答案:

答案 0 :(得分:2)

您可以使用联接或嵌套查询:

Select House.* from ((House join City on House.CityID = City.id)
                          join State on City.StateID = State.id)
                          join Country on State.CountryID = Country.id
               where Country.name = 'Australia'

Select * from House where CityID in (
    Select id from City where StateID in (
        Select id from State where CountryID in (
            Select id from Country where name = 'Australia'
        )
    )
)