bofett Posted February 9, 2009 Share Posted February 9, 2009 Please help. Table (cats) has id, name, parent. I am trying to echo the name of the parent when I know the id of the child. So for example… id name parent 1 Automotive NULL 2 Cleaning 1 3 Repair 1 I would like to display “ Automotive – Cleaning” When I know id=2. What is the best way to query for “Automotive”? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/ Share on other sites More sharing options...
fenway Posted February 9, 2009 Share Posted February 9, 2009 You'll have to "join" all the way up the chain -- which is difficult without a loop, SPs, or pre-existing knowledge. There's a sticky on hierarchical data. Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/#findComment-757916 Share on other sites More sharing options...
kkubek Posted February 10, 2009 Share Posted February 10, 2009 I'm too lazy to create the table to test this, but does this work ? select b.name, a.name from cats a, cats b where a.parent = b.id and a.id =2 Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/#findComment-758578 Share on other sites More sharing options...
aschk Posted February 10, 2009 Share Posted February 10, 2009 Google "Joe Celko's nested sets" for your answer. Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/#findComment-758845 Share on other sites More sharing options...
bofett Posted May 4, 2009 Author Share Posted May 4, 2009 This did the trick... function getCat($cat){ $qr1 = mysql_query("SELECT name FROM cats WHERE id='$cat'"); $a = mysql_fetch_object($qr1); return $a->name; } function getsubcat($cat){ $qr1 = mysql_query("SELECT parent FROM cats WHERE id='$cat'"); $a = mysql_fetch_object($qr1); if ($a->parent != "") { $qr2 = mysql_query("SELECT name FROM cats WHERE id=$a->parent"); $a2 = mysql_fetch_object($qr2); echo "{$a2->name} - "; }else{ } } Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/#findComment-825259 Share on other sites More sharing options...
Ken2k7 Posted May 4, 2009 Share Posted May 4, 2009 Which is a very long redundant version of: SELECT c1.name FROM cats c1 INNER JOIN cats c2 ON c1.id = c2.parent WHERE c1.id = $id right? Edit: my sql should be simplified but for some reason, I can't think right now. Quote Link to comment https://forums.phpfreaks.com/topic/144420-easy-query/#findComment-825262 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.