通过一个查询统计产品列表中的每个产品订单


Count each product orders in product listing with one query

mysql数据库中有两个表:

products: id, ...
products_order: id, pid,
                     ^
                 products.id

在产品列表页面中,如何显示每个产品的订单(例如,该产品由4个人订购(,而不必查询每个产品。例如

select count(*) from products_order where pid = 1

得到这样的结果:

pid    count
 1       5
 2       12
 3       1
 4       32
...     ...

由于那里有20的页码,我试过

SELECT COUNT(*) FROM products WHERE pid IN (1,2,3,4, ... 20)

但它并没有给我想要的。

使用此sql

SELECT pid, COUNT(pid) FROM products_order GROUP BY pid;