Skip to content
Advertisement

MYSQL – Join only the lastest row from the second table

I have patients table and appointments table. I want to query appointments from today and join patient info on the query.

This

JavaScript

Works, but it shows the first row it finds (usually the older one) not respecting the order by (to show only the latest by patient). What am I missing here?

UPDATE: Sorry, I should write it more properly.

Patient table:

JavaScript

Appointment table

JavaScript

If I query as I have it, the return will be

JavaScript

Instead of

JavaScript

Advertisement

Answer

Use window function for retrieving the patient wise latest date record. Then join patient table. If all patient info is needed then use LEFT JOIN instead of INNER JOIN.

JavaScript

Please check from url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=944f2dd72105bc9fb06b1a6b5fd837f2

For lower version where window functions are not supported.

JavaScript

Please check from url https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=d665ffe9f3d09df23513ad50be31b388

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement