【问题标题】:Count each product orders in product listing with one query一次查询统计产品列表中的每个产品订单
【发布时间】:2015-07-03 12:10:21
【问题描述】:

mysql db中有2个表:

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)

但它并没有给我想要的东西。

【问题讨论】:

  • 学习使用group by

标签: php mysql sql database codeigniter


【解决方案1】:

使用这个sql

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多