agora inbox for pgsql-sql@postgresql.org
help / color / mirror / Atom feedFrom: Thomas Kellerer <spam_eater@gmx.net>
To: pgsql-sql@postgresql.org
Subject: Re: Retrieve most recent 1 record from joined table
Date: Mon, 25 Aug 2014 07:59:18 +0200
Message-ID: <ltejbl$s1k$1@ger.gmane.org> (raw)
In-Reply-To: <53F6F9DA.4060005@gmail.com>
References: <53F6F9DA.4060005@gmail.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>
agharta schrieb am 22.08.2014 um 10:05:
> Joining the tables, how to get ONLY most recent record per table3(t3_date)??
>
> Query example:
>
> select * from table1 as t1
> inner join table2 t2 on (t1.t1_id = t2.t1_id and t2.t2_value like('%ab%') )
> inner join table3 t3 on (t2.t2_id = t3.t2_id and t3.t3_date <= timestamp '2014-08-20')
> order by t3.t2_id, t3.t3_date desc
>
This seems to be slightly faster, especially with the following index:
create index idx_t3_combined on table3 (t2_id, t3_date desc, t3_id);
select *
from table1 as t1
join table2 t2 on t1.t1_id = t2.t1_id and t2.t2_value like '%ab%'
join (
select distinct on (t2_id) t3_id,
t3_date,
t2_id
from table3
order by t2_id, t3_date desc
) t3 on t3.t2_id = t2.t2_id
order by t3.t2_id, t3.t3_date desc
;
I also had to increase the work_mem in order to avoid disk based sorting for the joins
--
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 (6+ messages) latest in thread
Message-ID: <ltejbl$s1k$1@ger.gmane.org>
Permalink: ../ltejbl$s1k$1@ger.gmane.org/
Also on: postgresql.org/message-id/ltejbl$s1k$1@ger.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: Retrieve most recent 1 record from joined table
In-Reply-To: <ltejbl$s1k$1@ger.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