EDIT
I cannot group by
only with patient_id
, I will get an error of sql_mode=only_full_group_by...
I
Just keep the group by clause t1.patient_id, t5.date_of_assessment
.
So I read this doc if you don't require order by order by assisment date remove it, or keep the same in group by also.
Solution 1: Change database to something using Window Functions, as apparently MySQL has big drawbacks on this field (for example). This could save your day
Solution 2: As probably the first solution won't be acceptable for you, you may try to use something like
select t1.patient_id, min(t3.date_of_visit) "date_of_visit"
from consultation t1
LEFT JOIN visit t3 ON t3.visit_id = t1.visit_id
group by t1.patient_id
You could join this as subquery or put it into some table (maybe even temporary). Join should be done by patient
and date_of_visit
then.
Unfortunatelly until you provide MCVE like Strawberry requests to, it will be hard to help more.
I think what you want is the first visit and last diabetes_assessment. I have assumed that the first field in all your tables is an auto_increment field and that consultation_id in the fiddle is incorrectly typed.
Given the above
MariaDB [sandbox]> select p.patient_name_en,v.*,c.diagnosis_id,d.diagnosis_name,da.date_of_assessment,da.assessment_result
-> from visit v
-> join patient p on p.patient_id = v.patient_id
-> join consultation c on c.patient_id = v.patient_id and c.visit_id = v.visit_id
-> join diagnosis d on d.diagnosis_id = c.diagnosis_id
-> left join
-> (
-> select da.patient_id, da.date_of_assessment,da.assessment_result
-> from diabetes_assessment da
-> where da.diabetes_assessment_id = (select max(da1.diabetes_assessment_id) from diabetes_assessment da1 where da1.patient_id = da.patient_id)
-> ) da on da.patient_id = v.patient_id
-> where v.visit_id = (select min(visit_id) from consultation c where c.patient_id = v.patient_id)
-> and c.diagnosis_id in (1,2)
-> and v.clinic_id = 361
-> ;
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
| patient_name_en | visit_id | patient_id | clinic_id | date_of_visit | visit_status | diagnosis_id | diagnosis_name | date_of_assessment | assessment_result |
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
| ABC | 1 | 361-9001 | 361 | 2017-03-03 | Active | 1 | Diabetes mellitus with diabetic nephropathy | 2017-05-05 | 40.00 |
| XYZ | 3 | 361-0361 | 361 | 2017-10-03 | Active | 2 | E01 Diabetes mellitus with kidney disease | 2017-03-10 | 30.50 |
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
2 rows in set (0.00 sec)