gpt4 book ai didi

sql - 在三个表上使用 count() 进行内连接

转载 作者:行者123 更新时间:2023-12-03 11:34:39 25 4
gpt4 key购买 nike

简单而快速的问题,我有这些表:

//table people
| pe_id | pe_name |
| 1 | Foo |
| 2 | Bar |
//orders table
| ord_id | pe_id | ord_title |
| 1 | 1 | First order |
| 2 | 2 | Order two |
| 3 | 2 | Third order |
//items table
| item_id | ord_id | pe_id | title |
| 1 | 1 | 1 | Apple |
| 2 | 1 | 1 | Pear |
| 3 | 2 | 2 | Apple |
| 4 | 3 | 2 | Orange |
| 5 | 3 | 2 | Coke |
| 6 | 3 | 2 | Cake |

我需要有一个列出所有人的查询,计算订单数量和 总计 项目数,例如:
| pe_name | num_orders | num_items |
| Foo | 1 | 2 |
| Bar | 2 | 4 |

但我不能让它工作!
我试过
SELECT
people.pe_name,
COUNT(orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;

但这会返回 num_*值不正确:
| name | num_orders | num_items |
| Foo | 2 | 2 |
| Bar | 8 | 8 |

我注意到,如果我尝试一次加入一张 table ,它会起作用:
SELECT
people.pe_name,
COUNT(orders.ord_id) AS num_orders
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
GROUP BY
people.pe_id;

//give me:
| pe_name | num_orders |
| Foo | 1 |
| Bar | 2 |

//and:
SELECT
people.pe_name,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN items ON (items.pe_id = people.pe_id)
GROUP BY
people.pe_id;
//output:
| pe_name | num_items |
| Foo | 2 |
| Bar | 4 |

如何将这两个查询合二为一?

最佳答案

将项目与订单加入比与人加入更有意义!

SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON orders.pe_id = people.pe_id
INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
people.pe_id;

与人们一起加入这些元素会引起大量的金币。
例如,订单 3 中的蛋糕项目将通过人与人之间的连接与订单 2 相关联,您不希望发生这种情况!!

所以 :

1- 您需要很好地了解您的架构。项目链接到订单,而不是人。

2-您需要为一个人计算不同的订单,否则您将计算与订单一样多的项目。

关于sql - 在三个表上使用 count() 进行内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3141463/

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