MySQL Forums
Forum List  »  PHP

Re: Query Problem
Posted by: Jay Pipes
Date: August 04, 2005 09:41PM

Instead of a correlated subquery, you could also use a single-pass derived table:

1) Gets client names and data of oldest linked record:

SELECT
client.Name
, client.Surname
, client_data.Data
FROM table2 as client
INNER JOIN table1 as client_data1
INNER JOIN (
SELECT ClientID, MIN(Number) as Number
FROM table1 AS client_data
GROUP BY ClientID
) as client_data2
ON client_data1.ClientID = client_data2.ClientID
AND client_data1.Number = client_data2.Number;


2) Gets client names and data of newest linked record:

SELECT
client.Name
, client.Surname
, client_data1.Data
FROM table2 as client
INNER JOIN table1 as client_data1
INNER JOIN (
SELECT ClientID, MAX(Number) as Number
FROM table1 AS client_data
GROUP BY ClientID
) as client_data2
ON client_data1.ClientID = client_data2.ClientID
AND client_data1.Number = client_data2.Number;


3) Gets client names and data of linked record with greatest time gap:

SELECT
client.Name
, client.Surname
, client_data.Data
FROM table2 as client
INNER JOIN table1 as client_data1
INNER JOIN (
SELECT ClientID, MAX(TO_DAYS(DateEnd) - TO_DAYS(DateBegin)) as DateDiff
FROM table1 AS client_data
GROUP BY ClientID
) as client_data2
ON client_data1.ClientID = client_data2.ClientID
AND client_data2.DateDiff = (TO_DAYS(client_data1.DateEnd) - TO_DAYS(client_data1.DateBegin));

Jay Pipes
Community Relations Manager, North America, MySQL Inc.

Got Cluster? http://www.mysql.com/cluster
Personal: http://jpipes.com

Options: ReplyQuote


Subject
Written By
Posted
August 04, 2005 07:30AM
August 04, 2005 07:51PM
August 04, 2005 07:53PM
Re: Query Problem
August 04, 2005 09:41PM
August 04, 2005 09:43PM
August 06, 2005 12:50AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.