If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > General > Database Concepts & Design > Traverse self-referencing table

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 08-23-10, 06:57
yunaki yunaki is offline
Registered User
 
Join Date: Aug 2010
Posts: 3
Traverse self-referencing table

Hello.

I have a self-referencing table like

column
id
description
parent_id

any know how can I Traverse the hierarchy table from a given id? thx

yunaki
Reply With Quote
  #2 (permalink)  
Old 08-23-10, 07:05
shammat shammat is offline
Registered User
 
Join Date: Nov 2003
Posts: 2,298
Using standard SQL, this can be solved using a recursive common table expression:
Code:
with traverse_tree (id, description, parent_id)  as 
(
   SELECT id, description, parent_id 
   FROM the_table_with_no_name
   WHERE id = 42
   
   UNION ALL

   SELECT t.id, t.description, t.parent_id 
   FROM the_table_with_no_name t
     JOIN traverse_tree p ON t.parent_id = p.id
)
SELECT *
FROM traverse_tree
Reply With Quote
  #3 (permalink)  
Old 08-23-10, 17:20
yunaki yunaki is offline
Registered User
 
Join Date: Aug 2010
Posts: 3
thanks answer.

I am a mysql user. does Mysql support "with" statement? I remember it did not. any idea in Mysql?
Reply With Quote
  #4 (permalink)  
Old 08-23-10, 18:11
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,085
Quote:
Originally Posted by yunaki View Post
any idea in Mysql?
mysql does not support common table expressions (CTEs) and i do not know whether or when it might do so

you might want to consider a query which has as many LEFT OUTER JOINs as there are levels in the hierarchy

see Categories and Subcategories
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #5 (permalink)  
Old 08-23-10, 18:18
shammat shammat is offline
Registered User
 
Join Date: Nov 2003
Posts: 2,298
Quote:
Originally Posted by yunaki View Post
I am a mysql user. does Mysql support "with" statement? I remember it did not. any idea in Mysql?
If you are using a specific DBMS, then you should post in that forum. I wouldn't have posted that answer in the MySQL forum...
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On