Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h3>Standard SQL solution</h3> <p>To get <em>two separate rows</em> (as later specified in the Q update) use a <a href="http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-UNION" rel="nofollow"><strong><code>UNION</code></strong></a> query: </p> <pre class="lang-sql prettyprint-override"><code>SELECT 'old' AS version, t1.id, t1.field1, t1.field2 FROM table1 t1 JOIN table2 t2 ON t2.table1_original_id = t1.id WHERE t2.id = $some_t2_id -- your t2.id here! UNION ALL SELECT 'new' as version, t1.id, t1.field1, t1.field2 FROM table1 t1 JOIN table2 t2 ON t2.table1_new_id = t1.id WHERE t2.id = $some_t2_id; -- your t2.id here! </code></pre> <p>Note: this is <em>one</em> query.<br> Returns as requested, plus a column <strong><code>version</code> to distinguish the rows</strong> reliably:</p> <pre class="lang-sql prettyprint-override"><code>version | id | field1 | field2 --------+----+--------+-------- old | 3 | blah | stuff new | 11 | more | things </code></pre> <h3>Faster Postgres-specific solution</h3> <p>A more sophisticated, but shorter and faster solution:</p> <pre class="lang-sql prettyprint-override"><code>SELECT version, id, field1, field2 FROM ( SELECT unnest(ARRAY['old', 'new']) AS version ,unnest(ARRAY[table1_original_id, table1_new_id]) AS id FROM table2 t2 WHERE t2.id = $some_t2_id -- your t2.id here! ) t2 JOIN table1 USING (id); </code></pre> <p>Same result.</p> <p><a href="http://sqlfiddle.com/#!11/3859e/8" rel="nofollow">-> SQLfiddle demo for both.</a></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.
 

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