简体   繁体   中英

Mysql query is really slow. How do I increase the speed of the query?

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM