内部连接只显示表中的第一行

f1tvaqid  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(323)

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

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

scu声明:

---------------------------------
|   id    |   code   |   mutation   |
|-----------------------------------|  
|    1    |    1     |     100      |
|    2    |    1     |     200      |
|    3    |    2     |     500      |
|    4    |    1     |     500      |
-------------------------------------

我要做的是选择表中的所有行 scu_banks 显示突变总数。数据应表示为:

--------------------------------------------------------------
| scu_banks.type | scu_banks.name |   total   | scu_banks.id |
--------------------------------------------------------------
|       1        |      One       | € 800.00  |      1       |
|       1        |      Two       | € 500.00  |      2       |
|       2        |     Three      | €   0.00  |      3       |
|       3        |      Four      | €   0.00  |      4       |
--------------------------------------------------------------

当我运行sql语句时,我得到以下数据:

---------------------------------------------------------------
| scu_banks.type | scu_banks.name |    total   | scu_banks.id |
--------------------------------------------------------------
|       1        |      One       | € 1300.00  |      1       |
---------------------------------------------------------------

我在这种情况下得到的数据是不正确的。€ 1300.00是表中所有突变的总和 scu_statement . 语句也不显示数据库中的其他行。
有人知道我的sql语句有什么问题吗?
下面是我的sql语句:

SELECT      scu_banks.type,
            scu_banks.name, 
            CONCAT('€ ', FORMAT(IFNULL(SUM(scu_statement.mutations), 0),2)) AS total, 
            scu_banks.id
FROM        scu_banks
INNER JOIN  scu_statement
ON          scu_banks.id = scu_statement.code
rqdpfwrv

rqdpfwrv1#

在子查询中进行聚合,然后将其左连接到banks。

SELECT b.type "scu_banks.type",
       b.name "scu_banks.name",
       concat('€ ', format(coalesce(x.mutation, 0), 2)) "total",
       b.id "scu_banks.id"
       FROM scu_banks b
            LEFT JOIN (SELECT s.code,
                              sum(s.mutation) mutation
                              FROM scu_statement s
                              GROUP BY s.code) x
                      ON x.code = b.id;

相关问题