MySQL Forums
Forum List  »  PHP

Re: Query Problem
Posted by: Roland Bouman
Date: August 04, 2005 07:51PM

Ok, all these queries need a join:

SELECT t2.name
, t2.surname
, t1.data
FROM table2 as t2
INNER JOIN table1 as t1
ON t2.clientid = t1.clientid

This gets all corresponding combinations of records from both tables. For each of your cases, you need to filter out those rows that interest you. If you MySQL version supports subqueries (>=4.1), you can do this like so:

SELECT t2.name
, t2.surname
, t1.data
FROM table2 as t2
INNER JOIN table1 as t1
ON t2.clientid = t1.clientid
WHERE t2.datebegin = (
SELECT min(t.datebegin)
FROM table2 as t
WHERE t.clientid = t2.clientid
)
So, we added a WHERE that requires that the datebegin of our joined table2 t2 equals the minimum databegin in table2 for that client. This would take query of query 1. To solve query 2, simply substitute max(t.datebegin) instead of min(t.datebegin). For the third query, its similar, but instead of comparing dates you must compare the difference of two dates:

SELECT t2.name
, t2.surname
, t1.data
FROM table2 as t2
INNER JOIN table1 as t1
ON t2.clientid = t1.clientid
WHERE t2.dateend- t2.datebegin = (
SELECT min(t.dateend- t.datebegin)
FROM table2 as t
WHERE t.clientid = t2.clientid
)

Options: ReplyQuote


Subject
Written By
Posted
August 04, 2005 07:30AM
Re: Query Problem
August 04, 2005 07:51PM
August 04, 2005 07:53PM
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.