🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.interbase.sql
Article #11093

Re: JOIN and max query

#11093
From: Craig Stuntz TeamB
Date: Thu, 12 Dec 2002 15:39
48 lines
2379 bytes
In article <3df8712d@newsgroups.borland.com>, "DP" <daveperkins@_woo-
hoo"-'#-bigfoot.com> says...
> 
> I asked something similar to this in the past, but even with the previous
> answer, this slight variation has me stumped (not hard to do)
> 
> TableA
> A_ID  integer
> Text varchar(100);
> 
> TableB
> B_ID      integer
> A_ID      integer
> Price       integer
> Changed TIMESTAMP
> 
> For every A_ID, I'd like the latest price (deduced by 'Changed') from
> Table_B.  There could be multiple(or zero) entries for A_ID in TableB.
> 
> I need the following columns:  A.A_ID,  A.Text,  B.Price, B.Changed
> 
> where  B.Price, B.Changed are the most recent entry in Table B.

SELECT
  A.A_ID, A.Text, B1.Price, B.Changed
FROM
  TableA A
  LEFT OUTER JOIN TableB B1
    ON (B1.A_ID = A.A_ID)
WHERE
  (B1.A_ID IS NULL) OR
  B1.Changed = (SELECT MAX(B2.Changed) FROM TableB B2
                WHERE (B2.A_ID = A.A_ID));

	This is a corellated subquery.  It runs once for each line in the 
result set.  Hence, if the result set is large your query will be slow.  
You can optimize this with a SELECTable stored proc if this becomes a 
problem.

	HTH,

	-Craig

-- 
Craig Stuntz [TeamB] � Vertex Systems Corp. � Columbus, OH
Delphi/InterBase Weblog : http://delphi.weblogs.com
InterBase Perf. Monitor : http://delphi.weblogs.com/IBPerformanceMonitor
InterBase PLANalyzer 1.1: http://delphi.weblogs.com/IBPLANalyzer
Technical Details
Message-ID: <MPG.186277cf430b97fa98a3b9@newsgroups.borland.com>
Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-06!sn-xit-09!supernews.com!newshosting.com!news-xfer1.atl.newshosting.com!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail
References: <3df8712d@newsgroups.borland.com>

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII
X-Google-Thread: 114a0e,54ae09d94673db75
X-Google-Attributes: gid114a0e,public
X-Google-ArrivalTime: 2002-12-12 07:55:43 PST
From: Craig Stuntz [TeamB] <cstuntz@nospamplease.com  (but use vertexsoftware to email)>
Newsgroups: borland.public.interbase.sql
Subject: Re: JOIN and max query
Date: Thu, 12 Dec 2002 10:39:51 -0500
Message-ID: <MPG.186277cf430b97fa98a3b9@newsgroups.borland.com>
References: <3df8712d@newsgroups.borland.com>
Organization: Vertex Systems Corporation
X-Newsreader: MicroPlanet Gravity v2.60
NNTP-Posting-Host: 65.86.87.242
X-Trace: newsgroups.borland.com 1039707599 65.86.87.242 (12 Dec 2002 07:39:59 -0800)
Lines: 48
Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-06!sn-xit-09!supernews.com!newshosting.com!news-xfer1.atl.newshosting.com!nntp-relay.ihug.net!newsfeeds.ihug.co.nz!ihug.co.nz!newsgroups.borland.com!not-for-mail