Note that there are some explanatory texts on larger screens.

plurals
  1. POdistinct records based on the most recent version
    primarykey
    data
    text
    <p>I list comments for an entry and I allow for user's to edit existing comments and it keeps track of those revisions.</p> <p>Table structure:</p> <p>comments: id, summary</p> <p>revisions: comment_id, revision_id, timestamp</p> <p>revisions.comment_id = comments.id</p> <p>revisions.revision_id = the id of the new comment, further explanation: when they select the existing comment, it will display an edit form and they may enter a new comment and submit it. It will insert it into the comments table as a new comment, grab the last id from that table and set it as revision_id in the revisions table.</p> <p>I want to do a select distinct on the revisions table (to retrieve multiple comment_id, revision_id into an array to be used within the application):</p> <p>for example: </p> <pre><code>select distinct comment_id from revisions </code></pre> <p>But is it possible to select the appropriate record based on the most recent comment (revisions.timestamp)?</p> <p>in theory:</p> <p>select distinct comment_id from revisions WHERE timestamp IS THE LARGEST</p> <p>revisions table example:</p> <pre><code>comment_id revision_id timestamp 2 12 20120222180000 2 13 20120222170000 5 18 20120222190000 5 19 20120222200000 </code></pre> <p>In this example of 4 rows, I'd want the query to return two rows,</p> <p>that being:</p> <p>comment_id = 2, revision_id = 12 timestamp = 20120222180000</p> <p>and</p> <p>comment_id = 5, revision_id = 19 timestamp = 20120222200000</p> <p>UPDATE: this seems to do the trick, but please let me know if there is a better way</p> <pre><code>SELECT distinct comment_id, max(timestamp) FROM revisions GROUP BY comment_id </code></pre> <p>UPDATE: I also need to include revision_id, the above query only includes comment_id and timestamp</p> <p>This did it:</p> <pre><code>SELECT distinct a.comment_id as comment_id, a.revision_id revision_id, a.timestamp as timestamp FROM REVISIONS a WHERE a.timestamp = ( SELECT max(b.timestamp) FROM revisions b WHERE b.comment_id = a.comment_id ) </code></pre>
    singulars
    1. This table or related slice is empty.
    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