agora inbox for pgsql-sql@postgresql.org  
help / color / mirror / Atom feed
From: Thomas Kellerer <spam_eater@gmx.net>
To: pgsql-sql@postgresql.org
Subject: Re: Most recent row
Date: Mon, 8 May 2017 14:19:14 +0200
Message-ID: <oepnns$bod$1@blaine.gmane.org> (raw)
In-Reply-To: <CAKFQuwb5ap3=_VvWOAnYG6E4aChk3jQTztube+UW=Kk29V01fQ@mail.gmail.com>
References: <201705050925.04194.gary.stainburn@ringways.co.uk>
	<CAKFQuwb5ap3=_VvWOAnYG6E4aChk3jQTztube+UW=Kk29V01fQ@mail.gmail.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>

David G. Johnston schrieb am 05.05.2017 um 17:14:
> ​I would start with something using DISTINCT ON and avoid redundant
> data. If performance starts to suck I would then probably add a field
> to people where you can record the most recent assessment id and
> which you would change via a trigger on assessments.
> 
> (not tested)​
> 
> ​SELECT DISTINCT ON (p) p, a
> FROM people p
> LEFT JOIN ​assessments a USING (p_id)
> ORDER BY p, a.as_timestamp DESC;
> 
> David J.
> 

I would probably put the evaluation of the "most recent assessment" into a derived table:

  select *
  from people p
  join (
    select distinct on (p_id) *
    from assessments
    order by p_id, as_timestamp desc
  ) a on a.p_id = p.id;

In my experience joining with the result of the distinct on () is quicker then applying the distinct on () on the result of the join.





-- 
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql



view thread (17+ messages)

Message-ID: <oepnns$bod$1@blaine.gmane.org>
Permalink:  ../oepnns$bod$1@blaine.gmane.org/
Also on:    postgresql.org/message-id/oepnns$bod$1@blaine.gmane.org

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: spam_eater@gmx.net
  Subject: Re: Most recent row
  In-Reply-To: <oepnns$bod$1@blaine.gmane.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox