0

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?

1
  • Add some sample data and your expected result. Commented Jul 15, 2016 at 7:38

1 Answer 1

2

Use COUNT(DISTINCT col) if you want the number of unique members and apps within each brand group. 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.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.