Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1d7heN-0006MZ-Sd for pgsql-sql@arkaria.postgresql.org; Mon, 08 May 2017 12:20:27 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1d7heM-0006wl-PX for pgsql-sql@arkaria.postgresql.org; Mon, 08 May 2017 12:20:26 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1d7hdN-00055N-EB for pgsql-sql@postgresql.org; Mon, 08 May 2017 12:19:25 +0000 Received: from [195.159.176.226] (helo=blaine.gmane.org) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.84_2) (envelope-from ) id 1d7hdL-0002O2-BM for pgsql-sql@postgresql.org; Mon, 08 May 2017 12:19:24 +0000 Received: from list by blaine.gmane.org with local (Exim 4.84_2) (envelope-from ) id 1d7hdD-0003Gb-OW for pgsql-sql@postgresql.org; Mon, 08 May 2017 14:19:15 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: Most recent row Date: Mon, 8 May 2017 14:19:14 +0200 Lines: 29 Message-ID: References: <201705050925.04194.gary.stainburn@ringways.co.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Complaints-To: usenet@blaine.gmane.org User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.23) Gecko/20090812 Thunderbird/2.0.0.23 Mnenhy/0.7.6.666 In-Reply-To: Content-Language: en-GB X-Host-Lookup-Failed: Reverse DNS lookup failed for 195.159.176.226 (failed) X-Pg-Spam-Score: -0.9 (/) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-sql Precedence: bulk Sender: pgsql-sql-owner@postgresql.org 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