Postgres 8.4 or higher
Starting with a particular GeoNames id (in this case 6429727) get its name and the name and id of each place containing it all the way up the hierarchy:
Code:
WITH RECURSIVE geonametree AS
(SELECT geoname.geonameid AS id, geoname.name AS name, hierarchy.parentid AS parent, hierarchy.childid AS child
FROM hierarchy
JOIN geoname ON geoname.geonameid = hierarchy.childid
WHERE geoname.geonameid = 6429727
UNION ALL
SELECT geoname.geonameid AS id, geoname.name AS name, hi.parentid AS parent, hi.childid AS child
FROM hierarchy AS hi
JOIN geoname ON geoname.geonameid = hi.parentid
INNER JOIN geonametree AS gt ON (hi.childid = gt.parent)
)
SELECT id, name, parent, child
FROM geonametree;