Php 在循环中计数?

Php 在循环中计数?,php,mysql,Php,Mysql,我需要选择所有产品: select id, data, name from products where user= ? 在一段时间内,我打印了以下结果: while{ product name, data ... } 问题是,我需要统计每种产品的销售量。 因此,在这段时间内,我有另一个选择,只是为了计数: while{ select count(id) from sells where product_id = id product name, data, sel

我需要选择所有产品:

select id, data, name from products where user= ?
在一段时间内,我打印了以下结果:

while{
product name, data
...
}
问题是,我需要统计每种产品的销售量。 因此,在这段时间内,我有另一个选择,只是为了计数:

     while{
select count(id) from sells where product_id = id
        product name, data, sells count
        ...
        }

所以我的问题很简单,我能在循环中避免这个计数吗?我能在第一次选择中只计算一次而不分组我的结果吗?

当问问题时,每次实际代码都比伪代码强…首先进行查询。然后根据迭代的结果。不要将sql查询放在while循环中。@CodeGodie你能给我一个例子吗?这是一个很好的注意,他们是如何首先进行查询的,然后根据你迭代的结果进行查询的。
select products.id, data, name, count(sells.id) as sell_count
from products 
left join sells on sells.product_id=products.id 
where user= ?
group by products.id