dongshuzui0335 2018-05-31 19:26
浏览 194
已采纳

2个COUNT个查询将结果相乘

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 i.e.: 3 x 5 = 15

  • 写回答

2条回答 默认 最新

  • douwen2158 2018-06-01 06:13
    关注

    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`;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?