r/SQL • u/danlindley • 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_id | name | species | sex | presenting |
|---|---|---|---|---|
| 1 | dave | walrus | female | captured |
| 2 | steve | guinea pig | male | injured |
(example of the table i wish to join)
| obs_id | patient_id | obs_date | obs_severity_score | obs_bcs_score | obs_age_score |
|---|---|---|---|---|---|
| 1 | 1 | 1/1/25 | 1 | 2 | 1 |
| 2 | 1 | 1/2/25 | 1 | 2 | 1 |
| 3 | 2 | 1/3/25 | 1 | 1 | 1 |
| 4 | 1 | 1/4/25 | 1 | 1 | 1 |
Desired output
| admission_id | name | species | sex | presenting | obs_date | obs_severity_score | obs_bcs_score | obs_age_score |
|---|---|---|---|---|---|---|---|---|
| 1 | dave | walrus | female | captured | 1/4/25 | 1 | 1 | 1 |
| 2 | steve | guinea pig | male | injured | 1/3/25 | 1 | 1 | 1 |
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 ASCThis 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 1any help would be really appreciated.
Dan
View all comments
Show parent comment
1
u/Yavuz_Selim Aug 12 '25
The reason why I gave an example ON condition is because you didn't post all your tables. In your first query, you mention these tables:
rescue_admissionsandrescue_patients. In your second query, you mentionrescue_observations.So, your queries mention 3 tables, however, you only give examples of 2 tables (
rescue_admissionsandrescue_observations). So, therescue_patientsis missing, which means that I can guess at best...According to your query (
ON rescue_admissions.patient_id = rescue_patients.patient_id) there is apatient_idcolumn in therescue_admissionstable. I don't know ifrescue_observationshas any other key columns.Your example dataset has no links between them, there is no way to get to the desired output. The link with patient is missing (or there is
patient_idin admissions that missing in your example).In any case, can you post the query that you have?