mysql – 什么是替代连接查询

表:项目

+---+-----------+
|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_id,number_of_order,total_quantity,total_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与订单连接来解决吗?如果有,怎么样?

我想的另一种方法 –

>从订单中选择…
>从item_order中选择…
>根据应用层的要求进行组合和格式化

您可以假设,订单和item_order表会变得更大,哪种解决方案会更好?

最佳答案 由于从order到item_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表中的每一行执行查询,而派生表的查询虽然更复杂,但只执行一次.我还希望这比在应用程序层执行两个查询和组合的选项更快.

点赞