mysql 与更多连接表执行合并

mysql perform union with more join tables

如下图所示,我需要过滤所有有贷款和没有贷款的客户。

这是我的 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) ; 

但它仍然 returns 只有在这方面提供 loans.Any 帮助的人才会很感激。提前致谢。

您正在与 mst_customer 进行 LEFT JOIN ...所以即使没有客户,您也会得到所有 loan_management。

LEFT JOIN
    loan_management_app.mst_customer cum

尝试使用 RIGHT JOIN 也许:

RIGHT JOIN
    loan_management_app.mst_customer cum

此外,您可以使用该查询,从 'mst_customer' 开始使用所有左联接。类似的东西:

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

我希望最后一个对你有用:-)