r/SQL • • Aug 12 '25

MySQL Nested Query

Afternoon everyone,

1As a newbie to SQL/PHP I'm not very familiar with how to nest another query inside a query.

What I am hoping to achieve:

I wish to join a second table to another table and limit the join only to the last/most recent record

What have i tried?

I placed an additional join in however it duplicated the data from the main table for each of the records in that main table.

(example of admissions table)

admission_idnamespeciessexpresenting
1davewalrusfemalecaptured
2steveguinea pigmaleinjured

(example of the table i wish to join)

obs_idpatient_idobs_dateobs_severity_scoreobs_bcs_scoreobs_age_score
111/1/25121
211/2/25121
321/3/25111
411/4/25111

Desired output

admission_idnamespeciessexpresentingobs_dateobs_severity_scoreobs_bcs_scoreobs_age_score
1davewalrusfemalecaptured1/4/25111
2steveguinea pigmaleinjured1/3/25111

Current SQL query

Collects all needed data for the table and the current joins.

SELECT *,
      DATEDIFF(NOW(), rescue_admissions.admission_date) AS daysincare
      FROM rescue_admissions
      INNER JOIN rescue_patients
      ON rescue_admissions.patient_id = rescue_patients.patient_id
      WHERE rescue_patients.centre_id = :centre_id AND rescue_admissions.disposition = 'Held in captivity' 
      ORDER by daysincare DESC, current_location ASC

This is the query I have used elsewhere to get the score i need:

SELECT obs_date, obs_id, obs_severity_score, obs_bcs_score, obs_age_score,
       FROM rescue_observations AS o
      WHERE o.patient_id = :patient_id ORDER by obs_date DESC LIMIT 1

any help would be really appreciated.

Dan

6 Upvotes

18 comments sorted by

View all comments

1

u/Time_Advertising_412 Aug 18 '25

My original thought, based upon your spec for getting the most recent observation and the example of desired output, was a correlated sub-query like the following but maybe I was missing something more in your request. My apologies if that is the case.

SELECT admission_id,name,species,sex,presenting,obs_date,

obs_severity_score,obs_bcs_score,obs_age_score

FROM rescue_admissions

INNER JOIN rescue_patients AS rp1 ON admission_id = patient_id

WHERE obs_date =

(SELECT MAX(obs_date)

FROM rescue_patients AS rp2

WHERE rp2.patient_id = rp1.patient_id);

1

u/danlindley Aug 18 '25

There's a solution which works well in one of the comments. Thank you for your advice though.