2

Say I have the following table:

TABLE: category
 - category_id (PK)
 - parent_id (FK)
 - name

Given a value for category_id, how do I return the given category_id and all its descendants?

1

1 Answer 1

3

If you want a single level, you'd do a SELECT on the condition category_id = id OR parent_id = id - but with MySQL, you cannot get a complete tree with a single query.

You can write a stored procedure to go through all of the intermediate results and pick up sub-children, but that really isn't very neat.

Instead, you can redesign your table. On the MySQL developer site, there is a nice article about how you can store hierarchical data in a table, and provides a design which is much more flexible than simply using a parent_id.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for linking to that article, I was looking for it and going to post it, myself.

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.