Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

database - Count total number of order item of each order in mysql

I have one table like below

|order_item_id|order_id|customer_id|
|     2       |   30   |    9      | 
|     3       |   30   |    9      | 
|     4       |   30   |    9      | 
|     5       |   30   |    9      | 
|     11      |   32   |    9      | 
|     12      |   32   |    9      | 
|     13      |   32   |    9      | 

here i would like to count total number of order_item_id for each order_id using mysql. please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

select order_id, count(*) from t
group by order_id

Edit:

yes this one i knew it, but actually i would like to list out all related records as well, not just count. – user804457

After the requirements changed, then this seems to be what you're looking for:

select * from t t1
join (
  select order_id, count(*) aCount from t
  group by order_id
) t2
on t1.order_id = t2.order_id

Result:

+---------------+----------+-------------+--------+
| ORDER_ITEM_ID | ORDER_ID | CUSTOMER_ID | ACOUNT |
+---------------+----------+-------------+--------+
|             2 |       30 |           9 |      4 |
|             3 |       30 |           9 |      4 |
|             4 |       30 |           9 |      4 |
|             5 |       30 |           9 |      4 |
|            11 |       32 |           9 |      3 |
|            12 |       32 |           9 |      3 |
|            13 |       32 |           9 |      3 |
+---------------+----------+-------------+--------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...