gpt4 book ai didi

mysql - 什么是替代连接查询

转载 作者:可可西里 更新时间:2023-11-01 07:38:16 24 4
gpt4 key购买 nike

表:项目

+---+-----------+
|id | name |
+---+-----------+
| 1 | Product-A |
| 2 | Product-B |
+---+-----------+

表:订单

+---+-----+------------+
|id |price| orderer_id |
+---+-----+------------+
| 1 | 100 | 53 |
| 2 | 240 | 54 |
| 3 | 200 | 54 |
| 4 | 150 | 53 |
+---+-----+------------+

表:item_order

+----+--------+---------+----------+
| id |order_id| item_id | quantity |
+----+--------+---------+----------+
| 1 | 1 | 1 | 2 |
| 2 | 1 | 2 | 3 |
| 3 | 2 | 2 | 2 |
| 4 | 3 | 1 | 1 |
| 5 | 3 | 2 | 1 |
| 6 | 4 | 1 | 2 |
| 7 | 4 | 2 | 2 |
+----+--------+---------+----------+

要提取的内容:

对于每个orderer_idnumber_of_ordertotal_quantitytotal_price

+---------+-----------------+----------------+-------------+
| orderer | number_of_order | total_quantity | total_price |
+---------+-----------------+----------------+-------------+
| 53 | 2 | 9 | 250 |
| 54 | 2 | 4 | 440 |
+---------+-----------------+----------------+-------------+

当前方法: 使用相关子查询

select orderer_id as orderer, 
count(*) as number_of_order,
sum(select quantity from item_order where item_order.order_id = orders.id) as total_quantity,
sum(price) as total_price
from orders
order by orderer_id

item_order加入orders可以解决吗?如果是,如何?

我想到的另一种方法——

  1. 从订单中选择 ...
  2. 从 item_order 中选择 ...
  3. 应用层中按要求组合格式化

如您所料,ordersitem_order 表会变得更大,哪种解决方案更好?

最佳答案

由于从ordersitem_order的一对多关系,在子查询中执行聚合和JOIN到派生表:

SELECT o.orderer_id,
COUNT(o.id) AS number_of_order,
SUM(io.quantity) AS total_quantity,
SUM(o.price) AS total_price
FROM orders o
JOIN (SELECT order_id, SUM(quantity) AS quantity
FROM item_order
GROUP BY order_id) io ON io.order_id = o.id
GROUP BY o.orderer_id

输出:

orderer_id  number_of_order total_quantity  total_price
53 2 9 250
54 2 4 440

Demo on dbfiddle

我希望这比相关子查询更快,因为必须对 orders 表中的每一行执行该查询,而对派生表的查询虽然更复杂,但只执行一次。我还希望这比在应用程序层执行两个查询和组合的选项更快。

关于mysql - 什么是替代连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850847/

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