gpt4 book ai didi

mysql - 减去具有不同行数的不同表的两列

转载 作者:行者123 更新时间:2023-11-30 21:54:31 25 4
gpt4 key购买 nike

如何编写单个查询,按 product_id 给出 SUM(Entrance.quantity) - SUM(Buying.quantity) 组。

问题出在第一个或第二个表中不存在的行中。可以这样做吗?

入口:

+---+--------------+---------+
| id | product_id | quantity|
+---+--------------+---------+
| 1 | 234 | 15 |
| 2 | 234 | 35 |
| 3 | 237 | 12 |
| 4 | 237 | 18 |
| 5 | 101 | 10 |
| 6 | 150 | 12 |
+---+--------------+---------+

购买:

+---+------------+-------------+
| id | product_id | quantity|
+---+------------+-------------+
| 1 | 234 | 10 |
| 2 | 234 | 20 |
| 3 | 237 | 10 |
| 4 | 237 | 10 |
| 5 | 120 | 15 |
+---+------------+------------+

期望的结果:

+--------------+-----------------------+
| product_id | quantity_balance |
+--------------+-----------------------+
| 234 | 20 |
| 237 | 10 |
| 101 | 10 |
| 150 | 12 |
| 120 | -15 |
+--------------+-----------------------+

最佳答案

这很棘手,因为产品可能在一张表中,但不在另一张表中。一种方法使用 union allgroup by:

select product_id, sum(quantity)
from ((select e.product_id, quantity
from entrance e
) union all
(select b.product_id, - b.quantity
from buying b
)
) eb
group by product_id;

关于mysql - 减去具有不同行数的不同表的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45799368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com