I have two history tables that track changes in database values, using a revision id to track the individual changes. e.g.
Table 1:
rev | A | B
=================
1 | 100 | 'A'
4 | 150 | 'A'
7 | 100 | 'Z'
Table 2:
rev | C | D
==================
1 | 200 | True
5 | 0 | True
8 | 0 | False
The goal would be to merge the two tables into:
rev | A | B | C | D
===============================
1 | 100 | 'A' | 200 | True
4 | 150 | 'A' | 200 | True
5 | 150 | 'A' | 0 | True
7 | 100 | 'Z' | 0 | True
8 | 100 | 'Z' | 0 | False
The idea being that for for a given revision, I would take the values corresponding to that revision or the highest revision less than it.
The SQL query that comes to mind would be something akin to cross joining the two tables with constraint rev1 < rev2, then selecting rows using a subquery where rev1 = max(rev1) for each given rev2; unioning this query with its counterpart exchanging rev2 and rev1; and finally filtering out duplicates from where rev1 = rev2.
The questions are:
- Is there a name for this type of join?
- Is there an idiom for performing this type of join in SQL, or would it be better to do it programmatically (which would definitely be much simpler and possibly more efficient)?
SQL Fiddle