Reputation: 574
I want to the latest results for my patients. The following sql returns 69,000 results after 87 seconds in mysqlworkbench. I have made both 'date' and 'patientid' columns as index.
select Max(date) as MaxDate, PatientID
from assessment
group by PatientID
I think my table has approximately 440,000 in total. Is it because that my table is 'large'?
Is there a way to increase the speed of this query, because I will have to embed this query inside other queries. For example like below:
select aa.patientID, assessment.Date, assessment.result
from assessemnt
inner join
(select Max(date) as MaxDate, PatientID
from assessment
group by PatientID) as aa
on aa.patientID = assessment.patientID and aa.MaxDate = assessment.Date
The above will give me the latest assessment results for each patient. Then I will also embed this piece of code to do other stuff... So I really need to speed up things. Anyone can help?
Upvotes: 0
Views: 275
Reputation: 1270613
I wonder if this version would have better performance with the right indexes:
select a.patientID, a.Date, a.result
from assessemnt a
where a.date = (select aa.date
from assessment aa
where aa.patientID = a.patientID
order by aa.date desc
limit 1
);
Then you want an index on assessment(patientID, date)
.
EDIT:
Another approach uses an index on assessment(patient_id, date, result)
:
select a.*
from (select a.patient_id, a.date, a.result,
(@rn := if(@p = a.patient_id, @rn + 1,
if(@p := a.patient_id, 1, 1)
)
) as rn
from assessment a cross join
(select @p := -1, @rn := 0) params
order by patient_id desc, date desc
) a
where rn = 1;
Upvotes: 1