2个COUNT个查询将结果相乘

时间:2018-05-31 19:26:47

标签: php mysql sql

我试图在3个连接中执行两个COUNT语句。第一个Count显示正确的数字,但第二个似乎由于某种原因将计数加起来?我检查了标记为重复的链接,但该示例中没有任何JOINS。

SELECT
    COUNT(DISTINCT `outlet_id`) AS `outlets`,
    `prod_name`,
    COUNT(`purchased`) AS `vouchersleft`
FROM
    `prod_outlets` AS `po`
INNER JOIN `bb_products` AS `bbp` ON po.`product_id` = bbp.`prod_id`
INNER JOIN `vouchers` AS `v` ON v.`product_id` = bbp.`prod_id`
GROUP BY
    bbp.`prod_id`;

它应该显示的是3个分支和5个代金券。但它输出了3个分支和15个凭证。因此,第二个COUNT乘以第一个,即:3 x 5 = 15

2 个答案:

答案 0 :(得分:1)

从描述中我理解的是你得到了交叉产品,这就是为什么你得到了错误的数字为什么,我建议你在sun子句中计算你的计数,然后加入这个子句与你的主要查询

SELECT
    COUNT(DISTINCT `outlet_id`) AS `outlets`,
    `prod_name`,
    v.vouchersleft
FROM
    `prod_outlets` AS `po`
INNER JOIN `bb_products` AS `bbp` ON po.`product_id` = bbp.`prod_id`
INNER JOIN (
    SELECT product_id, COUNT(*) vouchersleft
    FROM vouchers
    GROUP BY product_id
) AS `v` ON v.`product_id` = bbp.`prod_id`
GROUP BY
    bbp.`prod_id`;

答案 1 :(得分:0)

 "SELECT COUNT(DISTINCT `outlet_id`) as `outlets`,
 `prod_name`,
 COUNT(distinct `purchased`) as `vouchersleft`
 FROM `prod_outlets` as `po`
 INNER JOIN `bb_products` as `bbp`
 ON po.`product_id` = bbp.`prod_id`
 INNER JOIN `vouchers` as `v`
 ON v.`product_id` = bbp.`prod_id`
 GROUP BY bbp.`prod_id`";