我使用此查询:
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的数字,以及期望为“33”的product_number
总数。
我该如何修复查询。
答案 0 :(得分:1)
使用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)
答案 1 :(得分:1)
使用COUNT(o.user_id)
表示唯一买家的数量,使用SUM(product_number)
表示product_number的总数。最后,GROUP BY o.user_id
。
SELECT
COUNT(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)
GROUP BY o.user_id