mysql - Is there anyway to get parent on self table in sql? -


i need like this in mysql database.

in case need from:

id | first_reference  | description 1  | -1               | root 2  | 1                | other_child 3  | -1               | root 4  | 2                | child 5  | 1                | other_child 6  | 3                | child 

i need return root childid, or child if childid refer root:

i tried this:

select parent.id  mytable child join mytable parent on child.first_reference = parent.id  parent.first_reference = '-1' , child.id = '6' 

but doesn't work

and tried solution select case:

  select    case first_reference    when '-1' id    else select rec.id         mytable rec         rec.id = main.first_reference    end 'root'   mytable main   childid = '6' 

but syntax error.

where wrong?

if else have problem solved simle left join:

select case when parent.id null child.id         else parent.id         end id table child  left join table parent on    ((parent.id = child.first_reference , parent.first_reference =  '-1') or    (child.first_reference = '-1' , parent.id = null))  child.id =  '6' 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -