Note that there are some explanatory texts on larger screens.

plurals
  1. POMerge a table and a change log into a view in PostgreSQL
    primarykey
    data
    text
    <p>My PostgreSQL database contains a table to store instances of a registered entity. This table is populated via spreadsheet upload. A web interface allows an operator to modify the information presented. However, the original data is not modified. All changes are stored in a separate table <code>changes</code> with the columns <code>unique_id</code>, <code>column_name</code>, <code>value</code> and <code>updated_at</code>.</p> <p>Once changes are made, they are presented to the operator by first querying the original table and then querying the change table (using instance ID and the latest change date, grouped by column name). The two results are merged in PHP and presented on the web interface. This is a rather rigid way of going about the task and I would like to keep all logic within SQL.</p> <p>I can easily select the latest changes for the table using the following query:</p> <pre><code>SELECT fltr_chg.unique_id, fltr_chg.column_name, chg_val.value FROM changes AS chg_val JOIN ( SELECT chg_rec.unique_id, chg_rec.column_name, MAX( chg_rec.updated_at ) FROM information_schema.columns AS source JOIN changes AS chg_rec ON source.table_name = 'instances' AND source.column_name = chg_rec.column_name GROUP BY chg_rec.unique_id, chg_rec.column_name ) AS fltr_chg ON fltr_chg.unique_id = chg_val.unique_id AND fltr_chg.column_name = chg_val.column_name; </code></pre> <p>And selecting the entries from the <code>instances</code> table is just as easy:</p> <pre><code>SELECT * FROM instances; </code></pre> <p>Now, if there was only a way of transforming the former result and substituting the resulting values into the latter, based on the <code>unique_id</code> and <code>column_name</code>, and still retaining the result as a table, the problem would be solved. Is this possible to do?</p> <p>I am sure that this is not the rarest of the problems and most likely, some systems do keep track of changes to the data in a similar way. How do they apply them back to the data if not through one of the the above described ways (current and sought solutions)?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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