mysql使用更多连接表执行联合

时间:2016-05-06 06:19:01

标签: mysql join union

如下图所示,我需要使用和不使用贷款过滤所有客户。

enter image description here

这是我的mysql查询:

SELECT
    cum.id,
    lhh.mst_customer_id,
    cum.first_name,
    cum.middle_name,
    cum.last_name,
    cum.name_ins,
    lhh.loan_amount,
    lhh.date_granted,
    lhh.loan_duration,
    lhh.status
FROM
    loan_management_app.trans_cus_has_loan_header lhh
LEFT JOIN
    loan_management_app.mst_customer cum
ON
    (
        lhh.mst_customer_id = cum.id)
UNION 
SELECT
    cum.id,
    lhh.mst_customer_id,
    cum.first_name,
    cum.middle_name,
    cum.last_name,
    cum.name_ins,
    lhh.loan_amount,
    lhh.date_granted,
    lhh.loan_duration,
    lhh.status
FROM
    loan_management_app.trans_cus_has_loan_header lhh
RIGHT JOIN
    loan_management_app.mst_customer cum
ON
    (
        lhh.mst_customer_id = cum.id)
INNER JOIN 
        loan_management_app.mst_loan lon
ON
    (
        lhh.mst_loan_id= lon.id)
INNER JOIN 
        loan_management_app.trans_loan_has_interest lhi
ON
        (lhi.mst_loan_id=lon.id)   
INNER JOIN loan_management_app.mst_interest mi
ON 
        (mi.id=lhi.mst_interest_id) ; 

但它仍然只返回有贷款的人。对此有任何帮助是值得的。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您正在与mst_customer进行LEFT JOIN ......所以即使没有客户,您也可以获得所有贷款管理。

LEFT JOIN
    loan_management_app.mst_customer cum

尝试使用RIGHT JOIN:

RIGHT JOIN
    loan_management_app.mst_customer cum

此外,您可以使用该查询,来自' mst_customer'与所有lefts连接。这样的事情:

SELECT * FROM mst_customer mc 
LEFT JOIN trans_cus_has_loan_header tchl ON mc.id = tchl.mst_customer_id
LEFT JOIN mst_loan ml ON ml.id = tchl.mst_loan_id
LEFT JOIN trans_loan_has_interest tlhi ON tlhi.mst_loan_id = ml.id
LEFT JOIN mst_interest mi ON mi.id = tlhi.mst_interest_id

我希望最后一个适合你: - )

相关问题