Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's no specific join type to handle that sort of query. You have to do it either as a complex query or programmatically. Below is an example of PL/PGSQL code for this problem, using your example data.</p> <pre><code>CREATE OR REPLACE FUNCTION getRev(OUT rev INT, OUT A INT, OUT B CHAR, OUT C INT, OUT D BOOL) RETURNS SETOF record STABLE AS $BODY$ DECLARE c1 SCROLL CURSOR FOR SELECT * FROM Table1 ORDER BY rev; c2 SCROLL CURSOR FOR SELECT * FROM Table2 ORDER BY rev; r1 Table1%ROWTYPE; r1c Table1%ROWTYPE; r2 Table2%ROWTYPE; r2c Table2%ROWTYPE; BEGIN OPEN c1; OPEN c2; FETCH c1 INTO r1; FETCH c2 INTO r2; r1c := r1; r2c := r2; WHILE r1 IS NOT NULL AND r2 IS NOT NULL LOOP CASE WHEN r1.rev = r2.rev THEN rev := r1.rev; A := r1.a; B := r1.b; C := r2.c; D := r2.d; FETCH c1 INTO r1c; FETCH c2 INTO r2c; CASE WHEN r1c.rev = r2c.rev THEN r1 := r1c; r2 := r2c; WHEN r1c.rev &lt; r2c.rev THEN r1 := r1c; FETCH PRIOR FROM c2 INTO r2c; ELSE r2 := r2c; FETCH PRIOR FROM c1 INTO r1c; END CASE; WHEN r1.rev &lt; r2.rev THEN WHILE r1c IS NOT NULL AND r1c.rev &lt; r2.rev LOOP r1 := r1c; FETCH c1 INTO r1c; END LOOP; rev := r2.rev; A := r1.a; B := r1.b; C := r2.c; D := r2.d; r1 := r1c; ELSE WHILE r2c IS NOT NULL AND r2c.rev &lt; r1.rev LOOP r2 := r2c; FETCH c2 INTO r2c; END LOOP; rev := r1.rev; A := r1.a; B := r1.b; C := r2.c; D := r2.d; r2 := r2c; END CASE; RETURN NEXT; END LOOP; CLOSE c1; CLOSE c2; RETURN; END $BODY$ LANGUAGE 'plpgsql'; </code></pre> <p>This should run in O(length(Table1) + length(Table2)).</p> <p>Note the tricky part in the "CASE WHEN r1.rev = r2.rev" : we have to choose on which table we continue the scan for the next iteration. The correct one is the one with the smallest rev value after the cursor, to get through all the rev numbers available in both tables. You could certainly get better performance by coding it in C or C++. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload