MYSQL:多表连接 - 对先前连接有条件

时间:2014-06-20 19:19:32

标签: mysql sql join

    MEMBERS_TABLE

    member_id
    ---------------------------------------------
    1


    ACCOUNTS_TABLE

    account_id  member_id
    ---------------------------------------------
    1               1


    INVESTMENTS_TABLE

    investment_id   account_id
    ---------------------------------------------
    1               1
    2               1


    FUNDS_TABLE

    fund_id     investment_id
    ---------------------------------------------
    1               1
    2               2

这是我目前的查询:

SELECT 
    m.member_id,
    a.account_id, 
    i.investment_id, 
    f.fund_id, 
    COUNT(a.account_id) AS member_accounts_total, 
    COUNT(i.investment_id) AS member_investments_total, 
    COUNT(f.fund_id) AS member_funds_total 
FROM members AS m
    LEFT JOIN accounts AS a ON m.member_id = a.member_id
    LEFT JOIN investments AS i ON a.account_id = i.account_id
    LEFT JOIN funds AS f ON f.fund_id = i.fund_id


我希望看到以下结果:
member_accounts_total:1
member_investments_total:2
member_funds_total:2

相反,我得到了这些结果:
member_accounts_total:2
member_investments_total:2
member_funds_total:2

我真的不想为此写多个查询。

1 个答案:

答案 0 :(得分:1)

只需要改变
COUNT(a.account_id) AS member_accounts_total,


COUNT( distinct a.account_id) AS member_accounts_total,

您获得2的原因是因为投资帐户的左连接会产生2条记录。要获得明确的成员数量,您需要添加好...不同。

请注意,您可能也遇到其他总计的问题(从长远来看,可能还需要明确...)说成员有多个帐户。你也可能得到奇怪的数字(如果每个账户都有相同的投资......你想要只看一次或两次这个数量吗?