Jump to content

Recommended Posts

Quick question: should be simple, but its escaping me:

 

I want to get a count of user_ids (not the user_ids themselves, just the number) of users in 2 groups. However, if a user in both groups, they only count for 1 (because you don't want to send them 2 emails). How do i get that number:

 

This query is returning the total count, regardless if a user is in 2 groups.

 

SELECT DISTINCT user_id, COUNT(user_id) AS total FROM group_members WHERE group_id IN (2,17)

 

any thoughts?

 

thanks!

Link to comment
https://forums.phpfreaks.com/topic/248869-only-count-users-of-groups-1-not-twice/
Share on other sites

SELECT DISTINCT user_id, COUNT(user_id) AS total FROM group_members WHERE group_id IN (2,17) GROUP BY user_id

 

That's returning a row for each user_id with the total number of groups they are in like this:

 

user id    total

42            1

53            2

65            1

 

So, theoretically i could get the total number of unique users by mysql_num_rows, but i'd like to just get that done in the query than wasting extra resources

 

any ideas?

 

thanks

no clear what exactly are you looking for as  a result... if you are looking just for the total number of users in both groups (without duplicates) this will do it

SELECT COUNT(DISTINCT user_id) as total FROM group_members WHERE group_id IN (2,17);

 

or are you looking for the list of user_id's  (without duplicates) and not matter to which group they belong?... in such case maybe this will work

(SELECT user_id FROM group_members WHERE group_id IN (2,17)
GROUP BY user_id
HAVING COUNT(user_id) = 1)
UNION
(SELECT user_id FROM group_members WHERE group_id IN (2,17)
GROUP BY user_id
HAVING COUNT(user_id) > 1)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.