Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MYSQL:多表联接-以上一个联接为条件_Mysql_Sql_Join - Fatal编程技术网

MYSQL:多表联接-以上一个联接为条件

MYSQL:多表联接-以上一个联接为条件,mysql,sql,join,Mysql,Sql,Join,这是我当前的查询: MEMBERS_TABLE member_id --------------------------------------------- 1 ACCOUNTS_TABLE account_id member_id --------------------------------------------- 1 1 INVESTMENTS_TABLE in

这是我当前的查询:

    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

我希望看到以下结果:
会员账户总数:1
会员投资总额:2
会员基金总额:2

相反,我得到了以下结果:
会员帐户总数:2个
会员投资总额:2
会员基金总额:2

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

只需更改
COUNT(a.account\u id)作为会员账户总数,


COUNT(不同的a.account\u id)作为会员账户总数,

您得到2的原因是,帐户到投资的左连接将产生2条记录。要获得不同的成员数,您需要添加好。。。与众不同


请注意,如果一个会员有多个账户,您可能也会对其他合计有问题(从长远来看,可能也需要不同的合计…)。您也可能会得到奇数计数(如果每个帐户有相同的投资…您想只看到一次或两次计数吗?

我从来没有想过要添加“DISTINCT”-::转眼::非常感谢!我真的很感激!!这是我个人为数不多的几次让自己使用distinct。否则应该使用Group by。但在这里,这没有意义。
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