Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to solve code duplication in the following PostgreSQL query?
    primarykey
    data
    text
    <p>I have a table Inputs and a derived table Parameters</p> <pre><code>CREATE TABLE Configurables ( id SERIAL PRIMARY KEY ); CREATE TABLE Inputs ( configurable integer REFERENCES Configurables( id ), name text, time timestamp, PRIMARY KEY( configurable, name, time ) ); CREATE TABLE Parameters ( configurable integer, name text, time timestamp, value text, FOREIGN KEY( configurable, name, time ) REFERENCES Inputs( configurable, name, time ) ); </code></pre> <p>The following query checks whether a parameter has been changed, or is not present yet, and inserts the parameter with a new value.</p> <pre><code>QString PostgreSQLQueryEngine::saveParameter( int configurable, const QString&amp; name, const QString&amp; value ) { return QString( "\ INSERT INTO Inputs( configurable, name, time ) \ WITH MyParameter AS \ ( \ SELECT configurable, name, time, value \ FROM \ ( \ SELECT configurable, name, time, value \ FROM Parameters \ WHERE (configurable = %1) AND (name = '%2') AND time = \ ( \ SELECT max( time ) \ FROM Parameters \ WHERE (configurable = %1) AND (name = '%2') \ ) \ UNION \ SELECT %1 AS configurable, '%2' AS name, '-infinity' AS time, NULL AS value \ )AS foo \ ) \ SELECT %1 AS configurable, '%2' AS name, 'now' AS time FROM MyParameter \ WHERE time = (SELECT max(time) FROM MyParameter) AND (value &lt;&gt; '%3' OR value IS NULL); \ \ INSERT INTO Parameters( configurable, name, time, value ) \ WITH MyParameter AS \ ( \ SELECT configurable, name, time, value \ FROM \ ( \ SELECT configurable, name, time, value \ FROM Parameters \ WHERE (configurable = %1) AND (name = '%2') AND time = \ ( \ SELECT max( time ) \ FROM Parameters \ WHERE (configurable = %1) AND (name = '%2') \ ) \ UNION \ SELECT %1 AS configurable, '%2' AS name, '-infinity' AS time, NULL AS value \ )AS foo \ ) \ SELECT %1 AS configurable, '%2' AS name, 'now' AS time, '%3' AS value FROM MyParameter \ WHERE time = (SELECT max(time) FROM MyParameter) AND (value &lt;&gt; '%3' OR value IS NULL); \ " ).arg( configurable ).arg( name ).arg( value ); } </code></pre> <p>How should I best solve the duplication of 2 the MyParameter subqueries?</p> <p>Any other tips on cleaning up a query like this</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.
 

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