MySQL Forums
Forum List  »  Newbie

How to perform such SQL?
Posted by: Heorhii Hryhoriev
Date: March 06, 2021 05:58PM

There is a table "Categories".

category_id | parent_id
------------------------
1| NULL
2| 1
3| 2
4| 3
5| NULL
6| 5

The parent_id field contains the ID of the parent category for each category.
I need to create a query that will return all rows from a category table except the one given and all of its child categories.

For example,
for category_id 1, should be selected lines with category_id [5, 6]
for category_id 2, should be selected lines with category_id [1, 5, 6]
for category_id 3, should be selected lines with category_id [1, 2, 5, 6]
for category_id 4, should be selected lines with category_id [1, 2, 3, 5, 6]
for category_id 5, should be selected lines with category_id [1, 2, 3, 4]
for category_id 6, should be selected lines with category_id [1, 2, 3, 4, 5]

If a category has parent_id is NULL, it means that it has no parent category.

Options: ReplyQuote


Subject
Written By
Posted
How to perform such SQL?
March 06, 2021 05:58PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.