Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TOP on INNER JOIN

I have a table FISH which has a JOIN on HEALTHCHECK.

FISH

ID | NAME 
----------------
1 | JAMES
2 | JOHN
3 | ERIC

HEALTHECK

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID | DATE | FISH_ID
-------------------
1 | 2022-03-01 | 1
2 | 2023-01-01 | 1
3 | 2021-01-03 | 2
4 | 2023-04-07 | 3

I want to select a fish and return only the most recent HEALTHCHECK.

I have tried emulating this answer with:

SELECT fish.name, fish.id
FROM FISH
JOIN HEALTH_CHECK
ON HEALTH_CHECK.FISH_ID =
   (
   SELECT TOP 1  HEALTH_CHECK.CATCH_DATE
   FROM HEALTH_CHECK
   WHERE FISH_ID = HEALTH_CHECK.FISH_ID
       );

But the syntax of that is not correct, and I only want to return a specific fish (fish.id=x).

How would I return a fish with selected fields from the newest Health Check ?

The database is H2.

>Solution :

I would use a pure join version here:

SELECT f.NAME, f.ID
FROM FISH f
INNER JOIN HEALTH_CHECK hc1 ON hc1.FISH_ID = f.ID
INNER JOIN
(
    SELECT FISH_ID, MAX(DATE) AS MAX_DATE
    FROM HEALTH_CHECK
    WHERE FISH_ID = <some ID>
    GROUP BY FISH_ID
) hc2
    ON hc2.FISH_ID = hc1.FISH_ID AND
       hc2.MAX_DATE = hc1.DATE
WHERE
    f.ID = <some ID>

A better approach might be to use ROW_NUMBER(), but only fairly recent versions of H2 support that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading