mysql - 从 2 个表中选择总数量

标签 mysql sql

在 MySQL 中我有 4 个表:

 - product(id)
 - order(id)
 - order_detail_1(id, product_id, order_id, qty)
 - order_detail_2(id, product_id, order_id, qty)

我想获取按产品分组的 2 个表(order_detail_1、order_detail_2)中销售的产品数量的总和

产品可以存在于 order_detail_1 中,但不能存在于 order_detail_2 中,反之亦然

我测试了这个查询并且它有效,但我想要一个没有联合和子查询的更简单的查询。

select tmp.product_id ,sum(tmp.qty)  from
(
(
select order_detail_1.product_id ,sum(order_detail_1.qty) 
from order_detail_1
    inner join order on order_detail_1.id_order = order.id
    where order_detail_1.product_id is not null
    group by order_detail_1.product_id
)
union all
(
select order_detail_2.product_id ,sum(order_detail_2.qty) 
from order_detail_2
    inner join order on order_detail_2.id_order = order.id
    where order_detail_2.product_id is not null
    group by order_detail_2.product_id
)
) tmp
group by tmp.product_id

最佳答案

看起来您没有使用 order 表,而是检查它是否存在,因此您可以使用 EXISTS()

SELECT p.product_id,sum(p.qty) as qty
FROM (SELECT product_id,qty,id_order FROM order_detail_1
      WHERE product_id IS NOT NULL
      UNION ALL 
      SELECT product_id,qty,id_order FROM order_detail_2
      WHERE product_id IS NOT NULL) p
WHERE EXISTS(SELECT 1 FROM order o 
             WHERE o.id = p.id_order)
GROUP BY p.product_id

关于mysql - 从 2 个表中选择总数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444319/

相关文章:

sql - Postgresql如何从没有索引或id的表中按列值删除重复的行

c# - 使用 Microsoft.SqlServer.Management.Smo 更改 SQL SERVER EXPRESS 2008 TCP 端口

php - NOT LIKE 多个 OR 语句?

php - 使用存储过程从数据库中选择?

MySQL SELECT * 究竟是如何工作的 MySQL/Query Efficiency

sql - 使用生成的 UUID 更新列

c# - 使用相同的参数化查询添加多个 SQL 值?

sql - 大型非规范化表优化

mysql - SQL 与列名连接

MySQL LEFT JOIN 计数列Join 3个表