0

Hi i want to select objects with postgres recursive. But i cannot guarantee that every data in the database is correct. So i'ts not impossible that an object has for example itself as parent id.

Is it possible to stop when an object already exists? What i've tried:

with recursive sumthis(myobjectid,parent_myobjectid) as (
    select myobjectid, parent_myobjectid
    from myobjectentity
    where myobjectid = 243358
    union all
    select C.myobjectid, C.parent_myobjectid
    from sumthis P
    inner join myobjectentity C on P.myobjectid = C.parent_myobjectid AND (P.myobjectid NOT IN (SELECT myobjectid FROM sumthis))

)

SELECT * FROM myobjectentity WHERE myobjectid IN (select myobjectid from sumthis)

AND

with recursive sumthis(myobjectid,parent_myobjectid) as (
    select myobjectid, parent_myobjectid
    from myobjectentity
    where myobjectid = 243358
    union all
    select C.myobjectid, C.parent_myobjectid
    from sumthis P
    inner join myobjectentity C on P.myobjectid = C.parent_myobjectid
    Limit 100

)

SELECT * FROM myobjectentity WHERE myobjectid IN (select myobjectid from sumthis)
1
  • 1
    This is a special case of non-repeating directed graph traversal. Thankfully as you discovered, recursive CTEs (used right) help with this. Commented Aug 4, 2014 at 15:34

1 Answer 1

1

Ok the answer is reasy, i just had to change

union all 

to

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

Comments

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.