1

I have data like this

enter image description here

and using this query I got right output

SELECT  id,
        nama,
        parent_id
FROM    (SELECT * FROM members
         ORDER BY parent_id, id) members,
        (SELECT @pv := '3') initialisation
WHERE   FIND_IN_SET(parent_id, @pv) > 0
AND     @pv := CONCAT(@pv, ',', id)

output :

enter image description here

but if I modified parent_id of member14 from parent 13 to 15, I got wrong output enter image description here

output : (less than 1 column that appears (Member14))

enter image description here

expect output :

id     nama     parent_id
8      Member8   3
13     Member13  8
15     Member15  13
14     Member14  15
3
  • Please include data as SQL or markdown tables, not images. Seems to work as expected - db<>fiddle. If using MySQL >= 8 you should switch to a recursive cte. Commented Dec 9, 2022 at 12:11
  • oh yeah thanks. but why in your db<>fiddle the last result can output Member14, but if I run query in mysql, the Member14 is not show? Commented Dec 9, 2022 at 12:18
  • What version of MySQL are you running? Please add your CREATE TABLE statement to your question. Commented Dec 9, 2022 at 12:28

1 Answer 1

1

That's because @pv variable is processed for each row and it did this respecting natural order of the table (id values). You can add @pv in result

id  name            pv
8   Member8     3   3,8
13  Member13    8   3,8,13
15  Member15    13  3,8,13,15

So when on 14 Member @pv don't have 15 id in it. So the constraint is that parent_id need to be less than id for each row.

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

2 Comments

yes, but can I still do without select a smaller parent_id? like my case

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.