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

Show parent comment

1

u/danlindley Aug 13 '25

Yeah the MariaDB thing was a bit of an issue but I'm glad you persevered in your help

Thank you. I'll probably make that adjustment, just in case.

Thanks again.

2

u/Yavuz_Selim Aug 13 '25

SQL has different flavors, that generally work the same with very minor differences. I'm more experienced with Transact-SQL, which is ever so slightly different than MariaDB's SQL.

 

:).