Created
July 27, 2012 20:04
-
-
Save terrafied/3190184 to your computer and use it in GitHub Desktop.
SQL query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
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
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.