left join返回错误的总数

kmbjn2e3  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我的数据库中有以下数据:
渣打银行

----------------------------
|  id  |   name   |  type  |
|  1   |   One    |   1    |
|  2   |   Two    |   2    |
|  3   |  Three   |   1    |
|  4   |  Four    |   1    |
----------------------------

四川大学银行对账单

--------------------------------------
|  type  | code | mutations | status |
|   1    |  1   |    100    |    1   |
|   1    |  1   |    100    |    0   |
|   1    |  1   |    -50    |    1   |
--------------------------------------

我要显示以下数据:

------------------------------------------------------
|  type  |   name   | status1 | status2 | total | id |
|   1    |   One    |    1    |    2    |  150  | 1  |
|   2    |   Two    |    0    |    0    |   0   | 2  |
|   1    |  Three   |    0    |    0    |   0   | 3  |
|   1    |   Four   |    0    |    0    |   0   | 4  |
------------------------------------------------------

status1应该表示status=0的行的总数,status2应该表示status=1的行的总数。
我使用以下语句:

SELECT b.type 'scu_banks.type', b.name 'scu_banks.name', count(l.status) 'status1', count(s.status) 'status2', concat('€ ', format(coalesce(x.mutations, 0), 2)) 'total', b.id 'scu_banks.id' 

FROM scu_banks b 

LEFT JOIN scu_bankstatement l 
ON l.code = b.id AND l.status = 0 

LEFT JOIN scu_bankstatement s 
ON s.code = b.id AND s.status = 1 

LEFT JOIN (SELECT s.code, sum(s.mutations) mutations 
           FROM scu_bankstatement s 
           GROUP BY s.code) x ON x.code = b.id 
           GROUP BY b.id, b.name, b.type

当我执行语句时,在“status1”和“status2”列中得到总计“2”:

------------------------------------------------------
|  type  |   name   | status1 | status2 | total | id |
|   1    |   One    |    2    |    2    |  150  | 1  |
|   2    |   Two    |    0    |    0    |   0   | 2  |
|   1    |  Three   |    0    |    0    |   0   | 3  |
|   1    |   Four   |    0    |    0    |   0   | 4  |
------------------------------------------------------

有人知道我为什么得到不正确的回答吗?

mv1qrgav

mv1qrgav1#

您将两次加入scu银行对账单,因此匹配行的行数将增加一倍。您不需要两次加入表。
还应注意,x.突变应通过以下方式纳入该组:

SELECT 
    b.type 'scu_banks.type', 
    b.name 'scu_banks.name', 
    sum(if(l.status=0, 1, 0)) 'status1', 
    sum(if(l.status=1, 1, 0)) 'status2', 
    concat('€ ', format(coalesce(x.mutations, 0), 2)) 'total', 
    b.id 'scu_banks.id' 
FROM scu_banks b 

LEFT JOIN scu_bankstatement l 
ON l.code = b.id
LEFT JOIN (SELECT s.code, sum(s.mutations) mutations 
           FROM scu_bankstatement s 
           GROUP BY s.code) x ON x.code = b.id 
GROUP BY b.id, b.name, b.type, x.mutations

相关问题