Question

I have a table like this .. here is the fiddle

         id          child_id
         1               2
         2               3
         3               0
         4               5
         5               7
         6               0
         7               0         

I need a simple mysql query cause (my table is large) that would show take an id for example if i search for id 7 then it will show 4,5,7 ids rows .. mean first to find 7's parent the if there any go for that id in this case its 5. then again check if its child of any then bring the parent too until we got a 0. And if we seacrh with 3 then it will show 1,2,3 rows in same manner ..

can any one help me with this by a simple solution .. thanks in advance

Was it helpful?

Solution

Try this query:

SELECT case when col2 is null then col1 
else col2 end as col FROM
(SELECT  @first as col1,@parent_id :=
    (
    SELECT id
    FROM    mytable
    WHERE   parent_id = @parent_id
    ) AS col2
FROM    (
    SELECT @parent_id := @first
    ) var2,
    (
    SELECT  @first := 7
    ) var1
STRAIGHT_JOIN
    mytable
WHERE   @parent_id IS NOT NULL)tab

SQL Fiddle

OTHER TIPS

The Oracle brand table server offers a hierarchical query feature. http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm But MySQL doesn't.

You can do this with a series of queries. But there's no marvelously elegant query syntax.

In MySQL also there is a hirerarchical structure,

Refer this, http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/

Hope this helps you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top