Skip to content

Instantly share code, notes, and snippets.

@terrafied
Created July 27, 2012 20:04
Show Gist options
  • Save terrafied/3190184 to your computer and use it in GitHub Desktop.
Save terrafied/3190184 to your computer and use it in GitHub Desktop.
SQL query
Tables:
-users
-timestamps
-enterprises
-enterprise_users
-user_id
-enterprise_id
Goal:
Trying to find a query for all users for a given enterprise, but only for users for ONLY that enterprise. In otherwords, if a user is part of more than one enterprise (can assume simply more than one enterprise_users record for that user_id), then I *don't* want that returned.
Query so far:
SELECT COUNT(*) AS count_all, enterprise_users.enterprise_id AS enterprise_users_enterprise_id FROM `users` INNER JOIN `enterprise_users` ON `enterprise_users`.`user_id` = `users`.`id` WHERE (users.created_at > date('2012-02-01') AND users.created_at < date('2012-03-01') AND enterprise_users.enterprise_id = 1) GROUP BY enterprise_users.enterprise_id HAVING count(enterprise_users.enterprise_id) < 2
But this returns zero results. I know the results for both "this enterprise" and "ONLY this enterprise"
@jmelesky
Copy link

How does this work?

SELECT users.user_id
FROM users, enterprise_users
WHERE
users.id = enterprise_users.enterprise_id
users.created_at > '2012-02-01' AND
users.created_at < '2012-03-01' AND
enterprise_users.enterprise_id = 1
GROUP BY users.user_id
HAVING count(*) < 2

@jmelesky
Copy link

SELECT users.user_id
FROM
users,
enterprise_users e1,
enterprise_users e2
WHERE
users.id = e1.user_id AND
users.id = e2.user_id AND
users.created_at > '2012-02-01' AND
users.created_at < '2012-03-01' AND
e1.enterprise_id = 1
GROUP BY users.user_id
HAVING count(distinct e2.enterprise_id) < 2

@terrafied
Copy link
Author

Fixed query that works:

SELECT users.id
FROM users, enterprise_users
WHERE
users.id = enterprise_users.user_id
AND users.created_at > '2012-02-01'
AND users.created_at < '2012-03-01'
AND enterprise_users.enterprise_id = 1
GROUP BY users.id
HAVING count(*) < 2

However, it returns ALL records, not the subset for users who have only one enterprise_user record.

@jmelesky
Copy link

with
alluserlist as (select user_id from enterprise_users where enterprise_id = 1),
onlyuserlist as (select user_id from alluserlist, enterprise_users
where alluserlist.user_id = enterprise_users.user_id
group by user_id having count() < 2)
select count(
)
from onlyuserlist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment