我使用这个查询:
SELECT
`o_p`.`id`,
`o`.`user_id` AS `buyer`,
`product_number`
FROM `order_products` `o_p`
LEFT JOIN `order` `o` ON o.id=o_p.id
WHERE (`o_p`.`product_id`='5') AND (`o`.`pay_status`=1)
然后我得到这个结果:
id buyer product_number
20 7 13
26 7 10
27 19 10
或者你可以在这个 link 看到结果
但我想计算买家的数量,预期为“2”,以及 product_number
的总数,预期为“33”。
我应该如何修复查询。
最佳答案
使用 count(distinct user_id)
作为独立买家的数量,使用 sum(product_number)
作为 product_number 的总数
select count(distinct o.user_id) as buyer_number,
sum(product_number) as product_number_total
from order_products o_p
left join order o on o.id=o_p.id
where (o_p.product_id='5') and (o.pay_status=1)
关于MySQL 在单个查询中获取 COUNT 和 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955153/