tags:

views:

36

answers:

2

I have a table that has location ids in parent child relationships. It is basically a hierarchy like:

State
  -County
     --City

The table maps the hierarchy with the following columns

parentID
childID
type

If I want to get all sub-locations for a given location that's straightforward, something like:

SELECT childID FROM locations_table WHERE parentID = 1234 AND type = 'county'

But, if I need to skip one child level (e.g. skip the county level and include just the cities for a specific state), I can't figure out what SQL would work best to do that.

Basically, I am trying to get the children of the children for a specific parentID but can't figure out how to get that in a single SQL statement.

A: 

Use a self-join

SELECT childID
FROM locations_table T1
JOIN locations_table T2 ON T1.parentid = T2.childid
WHERE T2.parentID = 1234 AND T1.type = 'county'
Mark Byers
Thanks very much. I'm probably doing something wrong, but I keep getting an empty set for the results when I know there are valid results there for the parent id. My SQL looks like: SELECT * FROM locations_table T1 JOIN locations_table T2 ON T1.parentID = T2.childID WHERE T2.parentID = 1234
Frank
@Frank: Remember that the "parentID" is actually the grandparent ID in this query.
Mark Byers
O.k. I found the problem, it needs to have the join line as: JOIN locations_table T2 ON T1.parentID = T2.parentID Thanks again.
Frank
@Frank: I'm surprised your modification works. It looks wrong. Perhaps I misunderstood your data model.
Mark Byers
Oops I have been doing more testing and that didn't actually work. I'm trying to find the grandchildren of the parent, and am not sure where I'm going wrong.
Frank
@Frank, in Mark Byers' code the value `1234` is for a state (while in your example it was for a county) - have you replaced it with a valid state ID? (Sorry if this is a dumb question!)
Mark Bannister
Thanks, I finally found out that I had a problem in my tables, and the basic code provided was fine. I appreciate all of the help.
Frank
A: 
SELECT city.childID FROM
  locations_table INNER JOIN
  locations_table AS county ON locations_table.childID = county.parentID 
    INNER JOIN
  locations_table AS city ON county.childID = city.parentID
  where city.type='city' and locations_table.parentid=1234
frag
Thanks very much for this.
Frank
is this what you wanted?
frag