【问题标题】:mysql perform union with more join tablesmysql 与更多连接表执行联合
【发布时间】:2016-05-06 06:19:00
【问题描述】:

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

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

但它仍然只返回有贷款的人。任何有关这方面的帮助都将是可观的。提前致谢。

【问题讨论】:

    标签: mysql join union


    【解决方案1】:

    您正在与 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
    

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

    【讨论】:

    • 这种情况下您不需要 UNION。如果您有另一个客户表,其中包含更多行(和相同的列),则必须对 customers_2 执行 UNION ALL 以获取这两个表的所有行。问候。
    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多