1

I have items with categories and those categories can also have categories how can I find the first parent. For example...

CategoriesTbl
CategoryId | CategoryName   | parent
-------------------------------------
1          | Category1      | 0
2          | Category2      | 1
3          | Category3      | 2

ItemsTbl
ItemId     | CategoryId
-------------------------------------
1          | 3

How could I do a select on the item and join it to the category table with the parent category (CategoryId = 1). The parent category could be nested infinitely deep.

2 Answers 2

2

MySQL does not support recursive SQL queries. But there are other ways to store such parent-child data that allow you to get whole trees using a single SQL query.

See also:

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

Comments

0

You might be able to use something like this as a starting point.

For Example,

Table

Rank chid parid

7 6

5 4

4 3

3 2

2 Null

My output should be

Rank chiid parid

1 5 4

2 4 3

3 3 2

4 2 Null

CODE SNIPPET:

declare @table table(child int, parid int)
insert into @table
select 7, 6 union all
select 5, 4 union all
select 4, 3 union all
select 3, 2 union all
select 2, null

;with list
( tLevel,
  child,
  parId
) as
( select
  1 as tLevel,
  child,
  parId
  from @table a
  where parId is null
  union all
  select
  tLevel + 1,
  b.child,
  b.parId
  from list a
  join @table b
   on b.parId = a.child
)
select
  rank() over(order by tLevel desc)
    as Rank,
  child,
  parId
from list



/* -------- Sample Output: --------
Rank                 child       parId
-------------------- ----------- -----------
1                    5           4
2                    4           3
3                    3           2
4                    2           NULL
*/

2 Comments

the question is tagged as MySQL, there is no with syntax
No with, no recursive queries and no over().

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.