Php mysql从具有相同id的行中选择计数
我使用mysql和php 我有两张桌子 “学校”表包含:学生id、产品id、学生名称 “产品”表包含:产品id、产品名称 我问了一个问题Php mysql从具有相同id的行中选择计数,php,mysql,sql,Php,Mysql,Sql,我使用mysql和php 我有两张桌子 “学校”表包含:学生id、产品id、学生名称 “产品”表包含:产品id、产品名称 我问了一个问题 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
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