Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My version uses a joint of the table MyObjects against a subset of itself, created by a subquery, and containing only the last generation for each object:</p> <pre><code>SELECT O.id,generation,value FROM MyObjects O, (SELECT id,max(generation) AS max_generation FROM MyObjects WHERE generation &lt;= $GENERATION_ID GROUP BY id) AS TheMax WHERE TheMax.max_generation = generation AND O.deleted is False ORDER BY generation DESC; </code></pre> <p>In the above query, the GENERATION_ID is hardwired. A way to parametrize it is to write a function:</p> <pre><code>CREATE OR REPLACE FUNCTION generation_objects(INTEGER) RETURNS SETOF MyObjects AS 'SELECT O.id,generation,value,deleted FROM MyObjects O, (SELECT id,max(generation) AS max_generation FROM MyObjects WHERE generation &lt;= $1 GROUP BY id) AS TheMax WHERE TheMax.max_generation = generation AND O.deleted is False;' LANGUAGE SQL; </code></pre> <p>Now, it works. With this table:</p> <pre><code>&gt; SELECT * FROM MyObjects; id | generation | value | deleted ----+------------+-------+--------- 1 | 1 | 99 | f 2 | 2 | 88 | f 1 | 3 | 77 | f 2 | 4 | 88 | t 3 | 5 | 33 | f 4 | 6 | 22 | f 3 | 7 | 11 | f 2 | 8 | 11 | f </code></pre> <p>I get:</p> <pre><code>&gt; SELECT * FROM generation_objects(1) ORDER by generation DESC; id | generation | value | deleted ----+------------+-------+--------- 1 | 1 | 99 | f &gt; SELECT * FROM generation_objects(2) ORDER by generation DESC; id | generation | value | deleted ----+------------+-------+--------- 2 | 2 | 88 | f 1 | 1 | 99 | f &gt; SELECT * FROM generation_objects(3) ORDER by generation DESC; id | generation | value | deleted ----+------------+-------+--------- 1 | 3 | 77 | f 2 | 2 | 88 | f </code></pre> <p>And then, at the following generation, object 2 is deleted:</p> <pre><code>&gt; SELECT * FROM generation_objects(4) ORDER by generation DESC; id | generation | value | deleted ----+------------+-------+--------- 1 | 3 | 77 | f </code></pre>
 

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