我正在尝试将多个表的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_type
,protection_type
和situation_type
,并将它们添加到返回的行中。
我可以从结果中获得legal_id
,protection_id
和situation_id
,但是legal_type
,protection_type
和situation_type
始终为空
编辑:说明
有5张桌子:
主要的unit
表和通过unit_situation_legal_protection
连接到unit
作为外键的unit_id
。
unit_situation_legal_protection
具有其他外键,例如legal_id
,protection_id
和situation_id
。它们的每个表都有一个单独的表,其中包含id
和type
。
因此情况表包含:situation_id
和situation_type
。
答案 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