Subject Re: [firebird-support] select query
Author Helen Borrie
At 12:10 PM 30/01/2010, you wrote:
>I know, very common question here but...
>
>Just to simplify the problem, two simple table:
>
>Person:
>ID, NAME
>
>Message:
>ID, PERSON_ID, SUBJECT, TIMESTAMP
>
>
>I would like to have SELECT, which returns:
>
>Person.NAME, Message.SUBJECT, Message.TIMESTAMP
>
>
>where the rows included in the SELECT results are the rows with the youngest TIMESTAMP for each NAME only. SELECT MAX does not work, because Message.SUBJECT values in the table are unique.
>
>Thanks for your comments/suggestions.

Assuming you are using Fb 2.0 or higher, have you tried a derived table to bypass the strictures on your unique SUBJECT?

1. Put a DESCENDING index on Message."TIMESTAMP"

then

2.
SELECT deriv.NAME, m.SUBJECT, deriv.MOST_RECENT
FROM MESSAGE m
JOIN
(select
M1.PERSON_ID,
P.NAME,
max( M1."TIMESTAMP" )
FROM MESSAGE M1
JOIN PERSON P
ON P.ID = M1.PERSON_ID
GROUP BY 1, 2) as deriv ( PERSON_ID, NAME, MOST_RECENT)

ON m.PERSON_ID = derv.PERSON_ID

(or some perhaps more efficient variation)

./heLen