简体   繁体   English

MySQL与更多的联接表执行联合

[英]mysql perform union with more join tables

As shown in below image I need to filter all the customers with and without loans . 如下图所示,我需要过滤所有有或没有贷款的客户。

在此处输入图片说明

Here is my mysql query : 这是我的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) ; 

But it still returns only the people with loans.Any help regarding this would be appreciable. 但是它仍然只返回有贷款的人,对此的任何帮助都是不小的。 Thanks in advance. 提前致谢。

You're doing a LEFT JOIN with mst_customer ... so you're getting all loan_management even if don't have customer. 您正在使用mst_customer进行LEFT JOIN ...因此,即使没有客户,您也可以获得所有的loan_management。

LEFT JOIN
    loan_management_app.mst_customer cum

Try to use RIGHT JOIN maybe: 尝试使用RIGHT JOIN也许:

RIGHT JOIN
    loan_management_app.mst_customer cum

Also, you can use that query, going from 'mst_customer' with all lefts joins. 另外,您可以使用从“ mst_customer”开始的所有左联接的查询。 Something like that: 像这样:

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

I hope this last one will work for you :-) 我希望最后一个对您有用:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM