0

First of all, sorry for the bad title. I am in little hurry and couldn't think of a better one.

Now I have a table like this -

category_id    name        parent_category_id
______________________________________
1              country     0
2              state       1
3              city        2
4              block       3

And I want results as -

Name        ParentCategory
___________________________
country     NULL
state       country
city        state
block       city

Now the logic is ParentCategory is category name whose category_id is equal to parent_category_id. (Not sure if I explained it properly) I tried a lot writing a query for this, but don't know how can I do it.

Any help would be most appreciated.

4 Answers 4

3

You want a JOIN of the table with itself:

SELECT child.name, parent.name FROM tbl AS child
    LEFT JOIN tbl AS parent
    ON (child.parent_category__id = parent.category_id);
Sign up to request clarification or add additional context in comments.

Comments

3
SELECT 
  child.name AS Name,
  parent.name AS ParentCategory
FROM
  yourTableName AS child
  LEFT JOIN yourTableName AS parent ON parent.category_id=child.parent_category_id

Comments

1
SELECT   c.name  Name,
         p.name  ParentCategory
FROM  t  c
LEFT JOIN t  p 
ON p.category_id=c.parent_category_id;

See this SQLFiddle

Comments

-1
SELECT t1.name, t2.name FROM table as t1 LEFT JOIN table as t2 ON t1.parent_category_id=t2.category_id

1 Comment

and this one (left join instead inner)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.