MySQL 从具有相同 ID 的行中选择计数


mysql select count from rows with same id

im 使用 MySQL 和 php。

我有2张桌子。

"学校"表包含:student_id、product_id、student_Name"产品"表包含:product_id、product_name

我做了一个查询

select  student_id, p.product_name as product_name, p.product_id
from school s join products p on s.product_id = p.product_id

结果显示如下:

student_id  | p_name | p_id
0001        | boots  | p1
0001        | boots  | p1
0001        | boots  | p1
0001        | boots  | p1
0002        | boots  | p1
0003        | boots  | p1
0001        | shorts | p2
0001        | shorts | p2
0001        | shorts | p2
0003        | jeans  | p3

我需要计算学生购买的产品数量,但我如何进一步查询,以便我可以实现如下:

student_id | p_name | count
0001       | boots  | 4
0002       | boots  | 1
0003       | boots  | 1
0001       | shorts | 3
0003       | jeans  | 1
select student_id, p.product_name as product_name, count(*) as count
from school s 
join products p on s.product_id = p.product_id
group by student_id, p.product_name