left join返回错误的总数

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

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

  1. ----------------------------
  2. | id | name | type |
  3. | 1 | One | 1 |
  4. | 2 | Two | 2 |
  5. | 3 | Three | 1 |
  6. | 4 | Four | 1 |
  7. ----------------------------

四川大学银行对账单

  1. --------------------------------------
  2. | type | code | mutations | status |
  3. | 1 | 1 | 100 | 1 |
  4. | 1 | 1 | 100 | 0 |
  5. | 1 | 1 | -50 | 1 |
  6. --------------------------------------

我要显示以下数据:

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

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

  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'
  2. FROM scu_banks b
  3. LEFT JOIN scu_bankstatement l
  4. ON l.code = b.id AND l.status = 0
  5. LEFT JOIN scu_bankstatement s
  6. ON s.code = b.id AND s.status = 1
  7. LEFT JOIN (SELECT s.code, sum(s.mutations) mutations
  8. FROM scu_bankstatement s
  9. GROUP BY s.code) x ON x.code = b.id
  10. GROUP BY b.id, b.name, b.type

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

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

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

mv1qrgav

mv1qrgav1#

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

  1. SELECT
  2. b.type 'scu_banks.type',
  3. b.name 'scu_banks.name',
  4. sum(if(l.status=0, 1, 0)) 'status1',
  5. sum(if(l.status=1, 1, 0)) 'status2',
  6. concat('€ ', format(coalesce(x.mutations, 0), 2)) 'total',
  7. b.id 'scu_banks.id'
  8. FROM scu_banks b
  9. LEFT JOIN scu_bankstatement l
  10. ON l.code = b.id
  11. LEFT JOIN (SELECT s.code, sum(s.mutations) mutations
  12. FROM scu_bankstatement s
  13. GROUP BY s.code) x ON x.code = b.id
  14. GROUP BY b.id, b.name, b.type, x.mutations
展开查看全部

相关问题