简体   繁体   中英

Join 3 tables and display records even if missing value from 3rd table

I want to join three tables with this query:

select *, max(working_dx.date_added), diagnosis_list.diagnosis as WorkingDiagnosis from working_dx 
    inner join ild on ild.id_incr=working_dx.pt_id
    inner join diagnosis_list on working_dx.dx_id = diagnosis_list.id
    group by pt_id";

I want all the records in ild table, even if no matching record in working_dx - if no match the value in WorkingDiagnosis would simply be blank.

The above query only gives me back records where working_dx.dx_id has a value. How do I do the JOIN statements to give me back all the records even if blank.

try this:

SELECT *, max(working_dx.date_added), 
(CASE WHEN diagnosis_list.id IS NULL THEN  "" ELSE diagnosis_list.diagnosis  END) as WorkingDiagnosis 
    FROM working_dx 
    INNER JOIN ild on ild.id_incr=working_dx.pt_id
    LEFT JOIN diagnosis_list on working_dx.dx_id = diagnosis_list.id
    GROUP BY pt_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