So let's say I'm trying to get a list of all my users who belong to a certain user group. Easy:
SELECT *
FROM users, usergroups
WHERE usergroups.user_group_id = 1
NOW, let's say I want to get a list of all users who belong to a certain user group AND who have an email that ends in .edu.
SELECT *
FROM users, usergroups
WHERE usergroups.user_group_id = 1
AND users.email LIKE '%.edu'
That works great. Now let's say we want to get all of the above, plus users belonging to user group 2--but we don't care about the second group's email addresses. This query doesn't work:
SELECT *
FROM users, usergroups
WHERE usergroups.user_group_id IN (1,2)
AND users.email LIKE '%.edu'
Because it filters users from the second group. Right now I'm doing something like this:
SELECT *
FROM users as usrs, usergroups as groups1, usergroups as groups2
WHERE (groups1s.user_group_id = 1 AND users.email LIKE '%.edu')
OR groups2.user_group_id = 2
This gives me the results I want, but I hate the way it looks and works. Is there a cleaner way to do this?
EDIT
I didn't include joins on my last iteration up there. Here's what the query should really look like:
SELECT *
FROM users as usrs JOIN
usergroups as groups1 on usrs.group_id = groups1.group_id JOIN
usergroups as groups2 on usrs.group_id = groups2.group_id
WHERE (groups1.user_group_id = 1 AND users.email LIKE '%.edu')
OR groups2.user_group_id = 2