使用多个表的左联接到一个表时,MySQL Query无法获得结果

时间:2018-09-12 06:22:58

标签: mysql sql

我正在尝试将多个表的LEFT JOIN用作单个表:

SELECT unit.unit_id,
       unit_situation_legal_protection.unit_situation_legal_protection_id,
       situation.situation_id,
       situation.situation_type,
       legal.legal_id,
       legal.legal_type,
       protection.protection_id,
       protection.protection_type,
       unit_situation_legal_protection.unit_situation_legal_protection_date_added,
       unit_situation_legal_protection.unit_situation_legal_protection_status
FROM unit
LEFT JOIN unit_situation_legal_protection ON unit.unit_id = unit_situation_legal_protection.unit_id
LEFT JOIN situation ON unit_situation_legal_protection.situation_id= situation.situation_id
LEFT JOIN legal ON unit_situation_legal_protection.legal_id = legal.legal_id
LEFT JOIN protection ON unit_situation_legal_protection.protection_id=protection.protection_id
WHERE unit_situation_legal_protection.unit_id = 146

我需要从各自的表中获取legal_typeprotection_typesituation_type,并将它们添加到返回的行中。

我可以从结果中获得legal_idprotection_idsituation_id,但是legal_typeprotection_typesituation_type始终为空

编辑:说明

有5张桌子:

主要的unit表和通过unit_situation_legal_protection连接到unit作为外键的unit_id

unit_situation_legal_protection具有其他外键,例如legal_idprotection_idsituation_id。它们的每个表都有一个单独的表,其中包含idtype

因此情况表包含:situation_idsituation_type

1 个答案:

答案 0 :(得分:0)

WHERE unit_situation_legal_protection.unit_id = 146从您的join中产生left join。删除where子句并将其添加到联接中:

SELECT unit.unit_id,
       unit_situation_legal_protection.unit_situation_legal_protection_id,
       situation.situation_id,
       situation.situation_type,
       legal.legal_id,
       legal.legal_type,
       protection.protection_id,
       protection.protection_type,
       unit_situation_legal_protection.unit_situation_legal_protection_date_added,
       unit_situation_legal_protection.unit_situation_legal_protection_status
FROM unit
LEFT JOIN unit_situation_legal_protection ON unit.unit_id = unit_situation_legal_protection.unit_id and unit_situation_legal_protection.unit_id = 146
LEFT JOIN situation ON unit_situation_legal_protection.situation_id= situation.situation_id
LEFT JOIN legal ON unit_situation_legal_protection.legal_id = legal.legal_id
LEFT JOIN protection ON unit_situation_legal_protection.protection_id=protection.protection_id