user1407837
user1407837

Reputation: 1

Category and subcategory through a single query

I have a table with fields id,pid,name.I want to fetch the data in the following format through a single query.

id- parent category name- name

Name would be either category or subcategory and parent category name would be none if its parent else will be parent category name.

Upvotes: 0

Views: 1579

Answers (2)

Ganesh Bora
Ganesh Bora

Reputation: 1153

You can use following query:

SELECT c.name,pc.name FROM category c left join category pc on c.pid = pc.id;

Upvotes: 0

k102
k102

Reputation: 8079

try this:

select t.id,
        tp.name as parent_category,
        t.name as category
from table t
full join table tp on tp.id = t.pid

Upvotes: 1

Related Questions