左连接在同一个表SQL内

时间:2017-08-29 15:09:21

标签: mysql sql

SELECT 

`_conf_cities`.`cityid`,
`_conf_cities`.`countryid`,
`_conf_cities`.`name_mkd`,
`_conf_cities`.`child_municipality`,
`_conf_cities`.`parent`,

`conf_countries`.`countryid`,
`conf_countries`.`alpha2`

FROM `_conf_cities`

LEFT JOIN `conf_countries` ON `_conf_cities`.`countryid` = `conf_countries`.`countryid`

LEFT JOIN `_conf_cities` ON  `_conf_cities`.`cityid` = `_conf_cities`.`parent`

WHERE `_conf_cities`.`child_municipality` = '0'

当我尝试LEFT JOIN _conf_cities时,会出现问题。

这可以用另一种方式完成吗?

1 个答案:

答案 0 :(得分:2)

您必须使用别名,例如:

SELECT 
_conf_cities.cityid,
_conf_cities.countryid,
_conf_cities.name_mkd,
_conf_cities.child_municipality,
_conf_cities.parent,
conf_countries.countryid,
conf_countries.alpha2,
t2.cityid -- Now you can use alias
FROM _conf_cities
LEFT JOIN conf_countries ON _conf_cities.countryid = conf_countries.countryid
LEFT JOIN _conf_cities AS t2 ON  _conf_cities.cityid = t2.parent
WHERE
    _conf_cities.child_municipality = '0'
    AND t2.child_municipality = '0' -- Also you can use alias here