即使第3个表中缺少值,也要加入3个表并显示记录

时间:2017-01-16 18:01:06

标签: php mysql

我想用这个查询加入三个表:

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";

我想要ild表中的所有记录,即使在working_dx中没有匹配的记录 - 如果不匹配,WorkingDiagnosis中的值将只是空白。

以上查询仅返回working_dx.dx_id具有值的记录。如何处理所有记录,即使空白,我如何进行JOIN语句。

1 个答案:

答案 0 :(得分:0)

试试这个:

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;