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

用户名

我有3张桌子:

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

在该查询中,我得到这样的结果...代码B001在46中,在18中,代码B002在80中,在30中,代码B003在null中,在null中

如何解决这个问题?

Ashishmaurya

使用此查询

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

从多个表中选择并求和与联接和求和

来自分类Dev

MySQL从多个表中选择

来自分类Dev

从多个表中选择Mysql?

来自分类Dev

SQL从长表中选择不重复ID的情况

来自分类Dev

在表的多个列中选择重复的行

来自分类Dev

从多个表中选择,消除重复值

来自分类Dev

如何从mysql和php中的多个表中选择查询

来自分类Dev

MySQL-从多个表中选择而不产生重复数据

来自分类Dev

查询以从多个表中选择MySQL

来自分类Dev

MySQL:从多个表中选择数据

来自分类Dev

MySQL从表中选择父母和孩子

来自分类Dev

在多个表中选择

来自分类Dev

查询以从不同的表中选择不同的值,而不重复(显示为平面文件)

来自分类Dev

从两个联接表中选择具有最新日期而不重复的行?

来自分类Dev

MYSQL对多个表求和

来自分类Dev

在同一mongodb查询中选择按计数分组和不重复计数

来自分类Dev

MySQL从两个表匹配的多个表中选择

来自分类Dev

从表MySQL中选择最新的重复记录

来自分类Dev

Mysql 加入多个表和列重复

来自分类Dev

使用联接和计数从多个表中选择

来自分类Dev

MySQL从多个表中选择2个项目

来自分类Dev

从多个MYSQL表中选择嵌套数据

来自分类Dev

使用MySQL从Java中的多个表中选择前缀列

来自分类Dev

MySQL从多个表中选择并获得零计数

来自分类Dev

MySQL查询从多个表中选择数据进行比较

来自分类Dev

从表中选择多个ID

来自分类Dev

SQLite从多个表中选择*

来自分类Dev

从多个表中选择更新

来自分类Dev

从多个表中选择数据