X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 59928D1D206 for ; Wed, 21 Apr 2004 15:47:22 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 80175-08 for ; Wed, 21 Apr 2004 15:47:22 -0300 (ADT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id 7482ED1D10E for ; Wed, 21 Apr 2004 15:47:20 -0300 (ADT) Received: (qmail 31262 invoked by uid 500); 21 Apr 2004 18:51:22 -0000 Date: Wed, 21 Apr 2004 13:51:22 -0500 From: Bruno Wolff III To: Heflin Cc: pgsql-sql@postgresql.org Subject: Re: Join issue on a maximum value Message-ID: <20040421185122.GA31195@wolff.to> Mail-Followup-To: Heflin , pgsql-sql@postgresql.org References: <4086BD8E.90900@tampabay.rr.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <4086BD8E.90900@tampabay.rr.com> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at postgresql.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200404/211 X-Sequence-Number: 17586 On Wed, Apr 21, 2004 at 14:29:34 -0400, Heflin wrote: > > So a basic JOIN gets this: > > SELECT auction.auction_id, image.image_id, image.image_descr > FROM auction JOIN image ON auction.auction_id = image.auction_id > WHERE auction.auction_owner = 'Mabel'; > > Now the problem: I can't seem to remember how to get only the max value > for the image_id for each auction_id so that the result set would be: The postgres specific way of doing this is: SELECT DISTINCT ON (auction.auction_id) auction.auction_id, image.image_id, image.image_descr FROM auction JOIN image ON auction.auction_id = image.auction_id WHERE auction.auction_owner = 'Mabel' ORDER BY auction.auction_id, image.image_id DESC ; The more standard way to do it would be joining auction and image with a group by and max to get the highest image_id and then joining that result to image again to get the corresponding description.