条件左连接

时间:2014-01-26 08:27:31

标签: mysql

我正在试图弄清楚如何仅在需要时返回列。

1_finance_add_details

时,数据仅存在于e和地址t.trans_type=2表格中
SELECT t.*,
 a.company,
 a.house_number,
 a.flat_number,
 a.house_name,
 a.address1,
 a.address2,
 a.address3,
 a.town,
 a.county,
 a.post_code,
 a.country,
 f.*,
 e.company,
 e.house_number,
 e.flat_number,
 e.house_name,
 e.address1,
 e.address2,
 e.address3,
 e.town,
 e.county,
 e.post_code,
 e.country 
FROM 1_transactions t 
LEFT JOIN addresses a ON a.id=t.fk_addresses_id 
LEFT JOIN 1_finance_add_details f ON t.id=f.fk_transactions_id 
LEFT JOIN addresses e ON e.id=f.employ_fk_addresses_id 
WHERE trans_location=1 AND t.id=19;

1 个答案:

答案 0 :(得分:3)

不确定这是否是您想要的结果,但您可以在左连接中添加另一个条件,如下所示:

FROM 1_transactions t 
LEFT JOIN addresses a ON a.id=t.fk_addresses_id 
LEFT JOIN 1_finance_add_details f ON t.id=f.fk_transactions_id 
LEFT JOIN addresses e ON e.id=f.employ_fk_addresses_id AND t.trans_type=2
WHERE trans_location=1 AND t.id=19;

注意:这将使每个t的地址字段呈现为空,类型为!= 2。