简体   繁体   English

MySQL为多个计数选择返回相同的值

[英]MySQL returns same value for multiple count selects

I am trying to return multiple count values within a single query. 我试图在单个查询中返回多个计数值。 The query works but returns the same value for both of the count selectors: 该查询有效,但为两个计数选择器返回相同的值:

 $sql = 'SELECT '
            . '`b`.*,'
            . 'count(`ub`.`id`) `nummembers`,'
            . 'count(`ca`.`id`) `numapps` '
            . 'FROM '
            . '`brands` `b` '
            . 'LEFT JOIN `user_brands` `ub` ON `ub`.`brand_id`=`b`.`id` '
            . 'LEFT JOIN `ca` ON `ca`.`brand_id`=`b`.`id` '
            . 'GROUP BY `b`.`id`';

I sense I am missing a condition but not sure if the above is possible within a single query? 我感觉我错过了一个条件,但不确定在单个查询中是否可以实现以上条件?

Use COUNT(DISTINCT col) if you want the number of unique members and apps within each brand group. 如果要每个品牌组中的唯一成员和应用程序数量,请使用COUNT(DISTINCT col) The reason the counts were appearing the same in your original query is that you were counting the number of records in each group without regard to what is actually in each group. 计数在原始查询中显示相同的原因是,您在计算每个组中的记录数而又不考虑每个组中的实际记录。 This will always give you same number regardless of which ID you choose to count. 无论您选择计数哪个ID,它都会始终为您提供相同的号码。

SELECT b.*,
       COUNT(DISTINCT ub.id) nummembers,
       COUNT(DISTINCT ca.id) numapps,
FROM brands b
LEFT JOIN user_brands ub
    ON ub.brand_id = b.id
LEFT JOIN ca
    ON ca.brand_id = b.id
GROUP BY b.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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