Received: from maia.hub.org (maia-4.hub.org [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id EA002632979 for ; Wed, 26 May 2010 17:41:47 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 61298-09 for ; Wed, 26 May 2010 20:41:40 +0000 (UTC) X-Greylist: delayed 00:27:35.671514 by SQLgrey-1.7.6 Received: from cc.produs.ch (zux183-116.adsl.green.ch [80.254.183.116]) by mail.postgresql.org (Postfix) with ESMTP id 6DD0F632963 for ; Wed, 26 May 2010 17:41:39 -0300 (ADT) Received: from localhost (localhost.localdomain [127.0.0.1]) by cc.produs.ch (Postfix) with ESMTP id 21C44145B1E8; Wed, 26 May 2010 22:13:58 +0200 (CEST) Received: from orazio (unknown [192.168.181.11]) by cc.produs.ch (Postfix) with ESMTP id 839E2145B1E3; Wed, 26 May 2010 22:13:57 +0200 (CEST) From: "Luigi Antognini" To: "'Michele Petrazzo - Unipex'" , References: <4BFD5BC0.90900@unipex.it> Subject: Re: inner join and limit Date: Wed, 26 May 2010 22:13:36 +0200 Message-ID: MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Mailer: Microsoft Office Outlook 11 In-Reply-To: <4BFD5BC0.90900@unipex.it> Thread-Index: Acr8+wx913vIs6ZpQXmzz+LG5ukq/AAE7GTA X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5931 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=1.782 tagged_above=-5 required=5 tests=BAYES_50=0.8, RDNS_DYNAMIC=0.982 X-Spam-Level: * X-Archive-Number: 201005/116 X-Sequence-Number: 34164 Hello Here a suggestion for your problem. SELECT a.id AS t1_id, d.id AS t2_id, d.somedate AS t2_somedate FROM t1 a JOIN ( SELECT id, t1id, somedate FROM t2 b WHERE (t1id, somedate) IN ( SELECT t1id, somedate FROM t2 c WHERE c.t1id = b.t1id ORDER BY somedate DESC LIMIT 1 ) ) d ON (a.id=d.t1id); t1_id | t2_id | t2_somedate -------+-------+------------- 1 | 3 | 2010-05-25 2 | 5 | 2010-05-26 (2 rows) Hope this helps Regards (Saluti da Zurigo) Luigi Antognini -----Original Message----- From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-owner@postgresql.org] On Behalf Of Michele Petrazzo - Unipex Sent: Wednesday, May 26, 2010 7:35 PM To: pgsql-sql@postgresql.org Subject: [SQL] inner join and limit Hi list, I have two table that are so represented: t1: id int primary key ... other t2: id int primary key t1id int fk(t1.id) somedate date ... other data t1: 1 | abcde 2 | fghi data t2: 1 | 1 | 2010-05-23 2 | 1 | 2010-05-24 3 | 1 | 2010-05-25 4 | 2 | 2010-05-22 5 | 2 | 2010-05-26 I'm trying to create a query where the data replied are: join t1 with t2 and return only the LIMIT 1 (or N) of the t2, with date order (of t2). Data should be: t1.id | t2.id | t2,somedate 1 | 3 | 2010-05-25 2 | 5 | 2010-05-26 As said, I'm trying, but without success... Can be done for you? Thanks, Michele -- Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-sql