gpt4 book ai didi

左连接后MYSQL求和不同值

转载 作者:太空宇宙 更新时间:2023-11-03 11:37:03 26 4
gpt4 key购买 nike

我有这些表

/*OrderRows*/

order_id | row_id | article | quantity
1 | 1 | pen | 10
1 | 2 |scissors | 7
2 | 3 | book | 5
3 | 4 | pen | 5

/*Shipments*/

shipment_id | row_id | quantity_shipped
1 | 1 | 3
2 | 1 | 4
3 | 1 | 3
4 | 2 | 7
5 | 3 | 5
6 | 4 | 5

我需要生成一份报告来检查订单是否已完全发货

我希望使用左连接而不是子查询(只是为了检查:它是否更有效率?)

如果我问

SELECT
OrderRows.order_id,
sum(OrderRows.quantity) as ordered,
sum(Shipments.quantity_shipped) as shipped
FROM
Orders
LEFT JOIN Shipments ON OrderRows.row_id = Shipments.row_id
GROUP BY OrderRows.order_id

我显然得到了

order_id | orderered | shipped
1 | 27 | 17
2 | 5 | 5
3 | 5 | 5

那是因为左连接将我的 Orders.quantity 复制了三次 for order_id = 1(因为 order_id = 1 有 3 批货)

如何在不使用子查询的情况下获得它?

order_id | orderered | shipped
1 | 17 | 17
2 | 5 | 5
3 | 5 | 5

最佳答案

好吧,如果 ordered/quantity 是 order_id 的属性,那么只需选择它并group by

SELECT
Orders.order_id,
Orders.quantity as ordered,
sum(Shipments.quantity_shipped) as shipped
FROM
Orders
LEFT JOIN Shipments ON Orders.order_id = Shipments.order_id
GROUP BY Orders.order_id,orders.quantity

关于左连接后MYSQL求和不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060965/

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