0

I have the following table:

table 'users'

and I have the following query:

 WITH RECURSIVE users_r AS (
 SELECT user_id, parent_id, 0 as level
 FROM users
 WHERE parent_id is null
 UNION ALL
 SELECT u.user_id, u.parent_id, u.level + 1
 FROM users u
 INNER JOIN users_r
 ON (u.parent_id = users_r.user_id) 
 )
 SELECT * FROM users_r LIMIT 1000

I want to fill "level" column with depending on the count of ancestors. But my code isn't working. It fills rows only where parent_id is null.

Result of my code

asked Nov 7, 2016 at 11:23
1

1 Answer 1

1

It is a simple typo.

The recursive SELECT, immediately after the UNION ALL should not read

SELECT u.user_id, u.parent_id, u.level + 1

but

SELECT u.user_id, u.parent_id, users_r.level + 1

You would have noticed right away if you didn't have a level column in users.

answered Nov 7, 2016 at 11:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.