简体   繁体   中英

Need MySQL query that gets orders from main table, then a count of individual items associated with it as well as total rows from another table

I really need a MySQL query that gets orders from main table, then a count of individual items associated with it as well as total rows from another table.

So I have the following structure:

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

An order can have multiple SKUs and multiple lines per SKU per order. So what I am looking for and just can't figure out, is how to get the following:

order_number | count of individual skus from db.OrdersItems for order_number_id | total row count for order_number_id

ex.

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

I do believe you are after ( 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM