LEFT JOIN返回错误的总数

时间:2019-01-01 14:41:32

标签: mysql

我的数据库中有以下数据:

scu_banks

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

scu_bankstatement

--------------------------------------
|  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应该代表状态= 0的行总数,而Status2应该代表状态= 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  |
------------------------------------------------------

有人知道我为什么得到错误的答复吗?

1 个答案:

答案 0 :(得分:1)

您将两次加入scu_bankstatement,因此匹配行的行数将增加一倍。您不需要两次加入表。

还要注意,x.mutations应该包含在GROUP BY中:

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
相关问题