使用mysql银行系统中的左外连接无法获得准确的结果?

时间:2013-07-01 12:23:11

标签: mysql mysql-workbench

        SELECT
                    BB.NAME BranchName,
                    VI.NAME Village,
                    COUNT(BAC.CBSACCOUNTNUMBER) 'No.Of Accounts',
                    SUM(BAC.CURRENTBALANCE) SumOfAmount,
                    SUM(CASE
                        WHEN transactiontype = 'C' THEN amount
                        ELSE 0
                        END) AS CreditTotal,
                    SUM(CASE
                        WHEN transactiontype = 'D' THEN amount
                        ELSE 0
                        END) AS DebitTotal,
                    SUM(CASE
                        WHEN transactiontype = 'C' THEN amount
                        WHEN transactiontype = 'D' THEN - 1 * amount
                        ELSE 0
                        END) AS CurrentBalance

                FROM   CUSTOMER CU

                JOIN   APPLICANT AP
                ON     AP.CUSTOMER_CODE = CU.CODE

                JOIN   ADDRESS AD
                ON     AD.ENTITYCODE = AP.CODE

                JOIN   VILLAGE VI
                ON     VI.CODE           = AD.VILLAGE_CODE
                   AND VI.STATE_CODE     = AD.STATE_CODE
                   AND VI.DISTRICT_CODE  = AD.DISTRICT_CODE
                   AND VI.BLOCK_CODE     = AD.BLOCK_CODE
                   AND VI.PANCHAYAT_CODE = AD.PANCHAYAT_CODE

                JOIN   BANKBRANCH BB
                ON     BB.CODE = CU.BANKBRANCH_CODE

                JOIN   BANKACCOUNT BAC
                ON     BAC.ENTITYCODE = CU.CODE

                LEFT OUTER JOIN accounttransaction ACT 
                ON ACT.BANKACCOUNT_CBSACCOUNTNUMBER= BAC.CBSACCOUNTNUMBER
                   AND ACT.TRANDATE <= '2013-07-01'
                   AND BAC.ACCOUNTOPENINGDATE < '2013-07-01'

                WHERE  BAC.ENTITY = 'CUSTOMER'
                   AND AD.ENTITY = 'APPLICANT'

                GROUP BY BB.NAME,VI.NAME;

这里在BANKBRANCK表的一个分支中有263个账户,当我使用Left outer join执行上述查询时,计数增加到293,这是错误的,因为只有在该分支下打开的账户是263,结果是293,这是错误的。     如果我删除左外连接,那么当我包含Left out连接时,我的结果是263为一个分支,然后count增加到293,请帮助我在哪里出问题

   This is the continuous for the below question

    http://stackoverflow.com/questions/17277899/unable-to-get-left-outer-join-result-in-mysql-query/17279769#17279769   

1 个答案:

答案 0 :(得分:0)

本部分

LEFT OUTER JOIN accounttransaction ACT 
            ON ACT.BANKACCOUNT_CBSACCOUNTNUMBER= BAC.CBSACCOUNTNUMBER
               AND ACT.TRANDATE <= '2013-07-01'
               AND BAC.ACCOUNTOPENINGDATE < '2013-07-01'

允许返回accounttransaction表中的多行,这将允许行数从263增加到293. Left Join不会将联接数据隐式限制为仅一个匹配。