需要从主表获取订单的MySQL查询,然后是与其关联的单个项的计数以及来自另一个表的总行数

时间:2014-09-18 17:22:46

标签: mysql sql

我真的需要一个从主表获取订单的MySQL查询,然后是与其关联的单个项目的计数以及来自另一个表的总行数。

所以我有以下结构:

db.Orders
id | order_number | date_worked

1 | 1234 | 2014-09-17
2 | 1235 | 2014-09-17
3 | 1236 | 2014-09-17
4 | 1237 | 2014-09-17


db.OrdersItems
id | order_number_id | item_id

1 | 1234 | widget1
2 | 1234 | widget1
3 | 1234 | widget2
4 | 1234 | widget2
5 | 1234 | widget2
6 | 1235 | widget4
7 | 1235 | widget4
8 | 1236 | widget4
9 | 1236 | widget1
10| 1237 | widget1

每个订单每个SKU可以有多个SKU和多个行。所以我正在寻找并且无法弄清楚,如何获得以下内容:

order_number |来自db.OrdersItems的order_number_id |的单个skus计数order_number_id的总行数

离。

1234 | 2 skus | 5 lines
1235 | 1 skus | 2 lines
1236 | 2 skus | 2 lines
1237 | 1 skus | 1 lines

1 个答案:

答案 0 :(得分:1)

我相信你是在追求(SQL Fiddle):

SELECT o.order_number, COUNT(DISTINCT i.item_id) AS SkuCnt, COUNT(*) AS LineCnt
FROM Orders o
INNER JOIN OrdersItems i ON o.order_number = i.order_number_id
GROUP BY o.order_number