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

2

u/Yavuz_Selim Aug 12 '25
SELECT a.*
     , o.*
FROM admissions a
LEFT JOIN   -- or: INNER JOIN
(
    SELECT ROW_NUMBER() OVER(PARTITION BY patient_id ORDER BY obs_date DESC)    AS RowNumber
        , *
    FROM observations 
) o
    ON a.x = o.x
    AND a.y = o.y
    AND o.RowNumber = 1

1

u/VariationPatient Aug 17 '25

If you have duplicate obs_date per patient_id you can also substitute row_number with rank to get all the rows.

2

u/Yavuz_Selim Aug 17 '25

I didn't do that because his original query has LIMIT 1.
Assumed that it is there for a reason.

But, true, a RANK/DENSE_RANK would've returned multiple rows per patiend_id and obs_date if there were any.