MySQL从多个表中选择和求和,不重复
我有三张桌子:MySQL从多个表中选择和求和,不重复,mysql,sum,Mysql,Sum,我有三张桌子: 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 |
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
=======
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
=======
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
如何解决此问题?使用此查询
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
使用一个子查询、
UNION
子句和GROUP
ping,我构建了以下查询:
SELECT
p.code,
p.name,
-- Using IFNULL to handle products without stock variation
IFNULL(SUM(q.q_in), 0) AS total_in,
IFNULL(SUM(q.q_out), 0) AS total_out,
-- Compute the new stock level
p.qty + IFNULL(SUM(q.q_in), 0) - IFNULL(SUM(q.q_out), 0) AS qty
FROM (
-- UNION (= concatenate) prod_in and prod_out tables
SELECT
product,
qty AS q_in,
0 AS q_out -- Enforce schema (otherwise, q_out is dropped)
FROM prod_in
UNION
SELECT
product,
0 AS q_in,
qty AS q_out
FROM prod_out
) AS q
-- Using a RIGHT join to show products without stock variations
RIGHT JOIN products AS p
ON p.code = q.product
-- Group by id to get the summarized view
GROUP BY q.product
这里是一个带有示例数据的查询Use
left-outer-join
,您将得到B003的结果。对于其他错误结果,请尝试从中选择*。。。查看查询的结果。