简体   繁体   中英

Left Join inside the same table 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'

The problem occurs when I try to LEFT JOIN _conf_cities to itself.

Can this be done another way?

You have to use alias, like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM