1

I'm trying to get all children ids (multi levels) which are related to a parent. I thought using Recursive would do the trick, having attempted the query it's not returning the expected result and I'm not even sure this is the write way to go about this or where I'm going wrong.

Expected result is to return all cities and counties for a specified location.

For example if I pass the id for England (id=1) I'd like to return all the ids associated to it. It can be up to 4-5 level of association

For example

Id      Location
-----  ---------------
1      England
3      London            (as its associated with England)         
5      Ealing            (as associated with London)
6      Westminster       (as associated with London)
7      Camden            (as associated with London)
8      Barnet            (as associated with London)

. . .

SQL Fiddle example

Can someone please point me in the right direction on how to resolve this. Is this the correct way to approach this problem?

thanks.

david-l
  • 623
  • 1
  • 9
  • 20

2 Answers2

0

This tutorial gives a good overview of storing hierarchica data in sql.

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

Originally from this question: How do I represent a Tree Structure in a mySQL table

Community
  • 1
  • 1
Owen
  • 209
  • 1
  • 13
0

You are moving in the right direction.

Consider the result I've achieved:

;WITH locationFamily AS
(
    SELECT   id
            ,location_name 
            ,parent_id
            ,0 as level
    FROM location
    WHERE parent_id IS NULL
    and id = 1
    UNION ALL 
    SELECT   ls.id
            ,ls.location_name 
            ,ls.parent_id
            ,level + 1
    FROM location   ls
    INNER JOIN locationFamily  lf ON ls.parent_id= lf.id
)
SELECT *
FROM locationFamily 

move the id condition to the first select in the CTE, change aliases for id's connections.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142