我有一张如下表
|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 |
这里我想使用mysql计算每个order_id的order_item_id总数。 请帮忙
答案 0 :(得分:2)
试试这个:
select order_id, count(*) from t
group by order_id
修改强>
是的,我知道这个,但实际上我想列出所有相关记录,而不仅仅是计数。 - user804457
在要求发生变化之后,这似乎就是你要找的东西:
select * from t t1
join (
select order_id, count(*) aCount from t
group by order_id
) t2
on t1.order_id = t2.order_id
结果:
+---------------+----------+-------------+--------+
| 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 |
+---------------+----------+-------------+--------+
答案 1 :(得分:0)
select order_item_id, count(order_id)
from orders
group by order_id
答案 2 :(得分:0)
您需要使用GROUP BY
,如下所示:
SELECT order_item_id, COUNT(order_item_id) FROM your_table GROUP BY (order_id)
请参阅此处的官方文档:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html