tags:

views:

166

answers:

4

Quickie:

Table structure:

id | name | parent_id

I want to run a query for ID's, but also return that item's parent_id and the name of that id as well.

To better explain

SELECT id, name FROM sections

...then for each ID, return the ID and name of its parent using the "parent_id" column.

I'm trying to get this into an array:

[0]
    [id]
    [name]
    [parent_id]
    [parent_name]
+4  A: 

This should work:

SELECT s.id, s.name, s.parent_id, p.name as parent_name
FROM sections s LEFT JOIN sections p ON s.parent_id = p.id

Basically you just want to join the table against itself and bring in the name field as the parent name.

Josh
+1  A: 
SELECT a.id, a.name, b.id as parent_id, b.name as parent_name
FROM sections a
INNER JOIN sections b on a.parent_id = b.id

(could also do an outer join if there are nodes without parents)

ahockley
+1  A: 

just join the table to itself

something like:

SELECT child.id, child.name, child.parent_id, parent.name AS parentname FROM tablename child LEFT JOIN tablename parent ON child.parent_id = parent.id

SkippyFlipjack
+1  A: 

is doing a join more effective than simply doing subselects?

select id as childID , name as childName, parent_id as pid, (select id from sections where id = pid) as parentID, (select name from sections where id = pid) as parentName from sections;

the bigger issue is that this is non recursive... I'm curious how one would go about getting this to grow ad infinitum for relationships that are multi-generational.

Dr.Dredel
In this instance, the join should be faster (especially on large result sets). You are right though, you can't easily find a grand parent/child with this type of scheme. For that you either need recursion, or you could look into nested sets (Google: sql nested set model)
Josh
Another option would be to store the path to the child node in sql instead of just the parent id (eg /1/3/10 where 10 is the id of the parent, 1 is the id of the great-grand parent)
Josh