简体   繁体   中英

find last record of one to many relation on mysql with JOIN

I have four table in my database

Inspector: id,name,type,status,email

State: id,name,parent

Patient: id,name,age,national_code

Patient_Log: id,patient_id,inspector_id,state_id,breathing,body_movement,face_movement,gag,cough,cornea,pupil,doll_eye,sedation,status,update

i use this query now:

 SELECT patient.id, patient.name, patient.age, patient.national_code,
 pLog.id AS pLog_id, pLog.inspector_id, pLog.state_id, pLog.breathing, pLog.sedation,
 inspecor.name AS ins_name, inspecor.type AS ins_type, inspecor.status AS ins_status
 state.name AS state_name
 FROM patient
 JOIN patient_log AS pLog ON pLog.patient_id = patient.id AND pLog.id = 
 (SELECT MAX(patient_log.id) FROM patient_log WHERE patient_log.patient_id = patient.id)
 JOIN inspector ON inspector.id = pLog.inspector_id
 JOIN state ON state.id = pLog.state_id
 WHERE pLog.status = 1
 ORDER BY pLog.update DESC
 LIMIT 30

this Query it's work! and my result is true! but now my patient table have 1500 record and patient_log table have 8000 record with this Query i get the result in 16 second!!!!!!

if i remove this section from my query i get the result in 0.02 second but my result not true and return first record from patient_log:

 AND pLog.id = (SELECT MAX(patient_log.id) FROM patient_log WHERE 
 patient_log.patient_id = patient.id)

How can I optimize my query to get the correct result?

尝试在patient_log.patient_idpatient_log.id上添加复合索引

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