简体   繁体   中英

2 COUNT queries multiplying results

I am trying to execute two COUNT statements across 3 joins. The first Count shows the correct number but the second one seems to multiply the counts together for some reason? I checked the link which was marked as duplicate but that example doesn't have any JOINS in it.

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`;

What it should display is 3 branches and 5 vouchers. But it is outputting 3 branches and 15 vouchers. So, the second COUNT is multiplying by the first ie: 3 x 5 = 15

From the description what i understood is you are getting cross product that is why you are getting wrong number for vouchersleft, what i suggest you to calculate your count in a sun clause and then join this clause with your main query like

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`;
 "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`";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM