Mysql 内部联接只显示表中的第一行
我的数据库中有以下数据: 渣打银行:Mysql 内部联接只显示表中的第一行,mysql,sql,Mysql,Sql,我的数据库中有以下数据: 渣打银行: --------------------------------- | id | type | name | |-------------------------------| | 1 | 1 | One | | 2 | 1 | Two | | 3 | 2 | Three | | 4 | 3 |
---------------------------------
| 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 |
-------------------------------------
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
我要做的是选择表scu\u 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声明中所有突变的总和。该语句也不显示数据库中的其他行
有人知道我的sql语句有什么问题吗
以下是我的sql语句:
---------------------------------
| id | code | mutation |
|-----------------------------------|
| 1 | 1 | 100 |
| 2 | 1 | 200 |
| 3 | 2 | 500 |
| 4 | 1 | 500 |
-------------------------------------
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
在子查询中进行聚合,然后将其左键连接到银行
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;
解释计算总计的逻辑。这些突变是什么??还有xmen?你使用的是什么版本的mysql?