I have four related tables and, using the following query, combine them with 4 LEFT JOIN and 2 MAX() aggregate functions:
SELECT SQL_CALC_FOUND_ROWS
id,
cognome,
nome,
sesso,
pr_sedute_complessive,
presa_in_carico_data,
cf,
cnome,
tdr_cognome,
tdr_nome,
COUNT(tbl_trattamenti.trt_id),
MAX(tbl_trattamenti.data),
pr_id
FROM tbl_aziente p1
LEFT JOIN comuni
ON comuni.cid = p1.nascita_luogo
LEFT JOIN tbl_cartellaclinica
ON tbl_cartellaclinica.pz_fk_id = p1.id
LEFT JOIN tbl_progetto
ON tbl_progetto.cc_id_fk = tbl_cartellaclinica.cc_id
LEFT JOIN tbl_fisioterapista
ON tbl_fisioterapista.tdr_id = tbl_progetto.pr_fisioterapista_fk
LEFT JOIN tbl_trattamenti
ON tbl_progetto.pr_id = tbl_trattamenti.pr_fk_id
WHERE idoneo = 'y'
AND p1.tipo_assistenza = 4
GROUP BY p1.id
LIMIT 0, 10
This is all okay, except for one thing: I want the record from tbl_progetto which has the highest id rather than the first. I’ve tried to use MAX(primaryKey), but I then get only the key – not the record having that pKey.
The basic principle is that you need to reference
tbl_progettotwice – once in a subquery that identifies theidof the records of interest, and a second time to fetch the rest of that record.Assuming that there is a many-to-one relationship between
tbl_cartellaclinicaandtbl_progetto, the subquery would be:And therefore your modified query would be: