0

我使用 mysql 和 php。

我有 2 张桌子。

'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
4

1 回答 1

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
于 2013-11-06T02:29:50.853 回答