MySQL从多个表中进行选择和求和而不重复

标签 mysql sum

我有 3 张 table :

table1

code(Primary key) | name | quantity

B001 | sand | 50

B002 | nail | 100

B003 | paint | 10

=======

table2

code | qty_out

B001 | 2

B001 | 1

B001 | 20

B002 | 10

B002 | 30

=======

table3

code  | qty_in

B001   | 1

B001   | 5

B002   | 5

B002  | 10

=======

我想要的结果是:

table1

code  | name    | quantity  | Out      | In      | total

B001  | sand    | 50        | 23       | 6       | 33

B002  | nail    | 100       | 40       | 15     |  75

B003  | paint   | 10        | null/0  |  null/0  | 10

我使用了这个查询:

SELECT table1.code, table1.name, table1.quantity, sum(table2.qty_out ) AS 'Out', sum( table3.qty_in ) AS 'In'
FROM table1
LEFT JOIN table2 ON table2.code = table1.code
LEFT JOIN table3 ON table3.code = table1.code
GROUP BY table1.code
ORDER BY table1.code ASC

在该查询中,我得到这样的结果...code B001 out 46 and in 18, code B002 out 80 and in 30, code B003 out null and in null

如何解决这个问题?

最佳答案

使用此查询

select t.code,t.name,t.quantity,t.out,t.in,(t.out+t.in) as total
from ( 
      SELECT table1.code, table1.name, table1.quantity,
                ( select sum(table2.qty_out) 
                  from table2 
                  where table1.code=table2.code ) as out,
                ( select sum(table3.qty_in) 
                  from table3
                  where table3.code=table1.code ) as in  
      FROM table1
     ) as t

关于MySQL从多个表中进行选择和求和而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23731628/

相关文章:

MySQL:如何在一个查询中获取所有字段的 SUM()?

php - 将数据库导入 Google Cloud SQL 错误 : "mysql_query Duplicate entry ' 1' for key ' PRIMARY"

php - 从 MySQL 数据库导出数据到 PHP 中的 excel

php - 使用 AJAX 向 MySQL 插入值没有结果

function - 错误: 'Non-constructor pattern not allowed in sequential mode' (Isabelle)

sum - 任何有效的方法来计算第 n 项的谐波级数的总和? 1 + 1/2 + 1/3 + --- + 1/n =?

php - 查询多个表 MySQL 不同大小的 JSON 输出

MySQL - 哪种方法更好地检查列是否为 null 或空

python - 根据另一列的唯一值求和列的值

带有列表参数的 Python sum() 函数