Hi I got this table:

```
id   replacement id
1     2
2     1
2     3
3     2
2     4
4     2
10    11
11    10

```

The id(objects) are in a tree structure but the table is designed poorly for a tree structure.
The connection between the nodes goes both ways. 

The only way to determine if one is the parent of another is this table:

```
id  valid_until
1
2   2014-01-01
3   2013-01-01
4   2013-01-01
10  
11  2014-01-01

```

2 is parent of 3 and 4 because its valid\_until is later than 3 and 4. 1 is top node because it's still valid.

I'm struggling to write a query of this data so it could look like this:

```
id  parent
1
2   1
3   2
4   2 

```

Is there a way to make this as a single query or do I've to create a procedure and a temporary view for this?

**EDIT: I added some new rows to my table. So basically I also want to say in the query that I only want id: 1,2,3 or 4's tree not 10 and 11. How do I do that?**