Nikk
Nikk

Reputation: 7891

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?

Upvotes: 0

Views: 40

Answers (1)

cn0047
cn0047

Reputation: 17071

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

Upvotes: 2

Related Questions