2017-01-09 63 views
0

我有數據庫結構是怎樣的圖像下方在MySQL連接3個表來選擇字段

enter image description here

我想選擇所有的街道,與街道名稱,城市名稱,省名。我的代碼是這樣的:

SELECT province.name as province, city.name as city, subdistrict.name as subdistrict 
    from provinces province, cities city, subdistricts subdistrict 
    WHERE province.id = city.id AND city.id = subdistrict.id; 

,但我只得到儘可能多的總省份的數據並非所有的街道數據

回答

0

您基本的SQL缺少一個逗號,但一般應該工作。我強烈建議使用更現代化的連接語法: -

SELECT province.name AS province, 
     city.name AS city, 
     subdistrict.name AS subdistrict 
FROM provinces province 
INNER JOIN cities city 
ON province.id = city.id 
INNER JOIN subdistricts subdistrict 
ON city.id = subdistrict.id; 

然而,從你的描述,我不能確定,如果你正在嘗試做一些彙集處理?

+0

'SELECT province.name AS省, city.name AS城市, subdistrict.name AS街道 從省省 INNER JOIN城市城市 ON province.id = city.province_id INNER JOIN街道街道 ON城市.id = subdistrict.city_id;'這是正確的 –