我正在使用mysql和php。
我有两张桌子。'school'表包含:student_id,product_id,student_Name 'products'表包含: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
答案 0 :(得分:5)
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