-1

Let's say I have a Table people with the following columns:

name/string, mothers_hierachy/ltree
"josef", "maria.jenny.lisa"

How do I find all mothers of Josef in the people Table?

I'm searching for such a expression like this one: (That actually works)

SELECT * FROM people where name IN (
   SELECT mothers_hierachy from people where name = "josef"
)
John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

2

You can cast the names to ltree and then use index() to see if they are contained:

# select * from people;

┌───────┬───────────────────────┐
│ name  │   mothers_hierarchy   │
├───────┼───────────────────────┤
│ josef │ maria.jenny.lisa      │
│ maria │ maria                 │
│ jenny │ maria.jenny           │
│ lisa  │ maria.jenny.lisa      │
│ kate  │ maria.jenny.lisa.kate │
└───────┴───────────────────────┘
(5 rows)


# select *             
    from people j 
         join people m
           on index(j.mothers_hierarchy, m.name::ltree) >= 0
   where j.name = 'josef';

┌───────┬───────────────────┬───────┬───────────────────┐
│ name  │ mothers_hierarchy │ name  │ mothers_hierarchy │
├───────┼───────────────────┼───────┼───────────────────┤
│ josef │ maria.jenny.lisa  │ maria │ maria             │
│ josef │ maria.jenny.lisa  │ jenny │ maria.jenny       │
│ josef │ maria.jenny.lisa  │ lisa  │ maria.jenny.lisa  │
└───────┴───────────────────┴───────┴───────────────────┘
(3 rows)

Mike Organek
  • 11,647
  • 3
  • 11
  • 26