Which Hierarchical model should I use? Adjacency, Nested, or Enumerated?

前端 未结 2 921
礼貌的吻别
礼貌的吻别 2021-02-01 10:31

I have a table which contains a location of all geographical locations in the world and their relationships.

Here is a example that shows the hierarchy. You will see tha

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 11:25

    This is the query that I came up. It is an adaption of what you suggestion Quassnoi.

    SELECT   pa.*,  level, SUBSTRING_INDEX(p.ancestry, '/', l.level),  p.*
    FROM     geoplanet_places p
    JOIN     levels l
    ON       SUBSTRING_INDEX(p.ancestry, '/', l.level) <> p.ancestry 
    JOIN     geoplanet_places  pa
    ON       pa.woeid =  SUBSTRING_INDEX( SUBSTRING_INDEX(p.ancestry, '/', l.level),'/',-1)
    WHERE    p.woeid = "13911"
    

    This returns all of the parents of Brighton.

    The problem with your query was that it wasn't return the path to parents, but instead any node which shared the same path.

    SELECT     pa.*, GROUP_CONCAT(pa.name ORDER BY pa.lft asc),group_concat( pa.lft  ), pa.ancestry
                                                FROM     geo_places p
                                                JOIN     levels l
                                                ON       SUBSTRING_INDEX(CONCAT(p.ancestry, p.woeid,'/'), '/', l.level) <> p.ancestry 
                                                JOIN     geo_places  pa
                                                ON       pa.woeid =  SUBSTRING_INDEX( SUBSTRING_INDEX(CONCAT(p.ancestry, p.woeid,'/'), '/', l.level),'/',-1)
                                                WHERE    p.woeid IN ("12767488","12832668","12844837","131390","131391","12846428","24534461")
                                                GROUP BY p.woeid
    

提交回复
热议问题