Subject Re: [firebird-support] Confused about JOINS, and how to solve the following
Author Milan Babuskov
Richard Mace wrote:
> a list of group Id's, so I can ask firebird for all of the users belonging
> to these groups (then pass in the list of group Id's). (but I only want a
> user returned once, as it is possible that they are in more than one group
> that I am viewing)
>
> a table called users_groups with fields: Id, UserId and GroupId
> a table called users, which has an Id field (inteneded to be linked to
> UserId above)
> a table called groups, which also has an Id field (intended to be linked to
> the GroupId above)
>
> I am trying to write a query that will pull back each user, as described
> above, and am not sure how to do it?

There are at least four different ways to do it: You can use DISTINCT or
GROUP BY or EXISTS or IN.

select distinct userid
from users_groups
where group_id in (list of groups);

select userid
from users_groups
where group_id in (list of groups)
group by group_id;

select u.id
from users u
where exists (
select 1 from users_groups g
where u.id = g.userid
and group_id in (list of groups)
);

select u.id
from users u
where u.id in (select g.userid from users_groups g
where group_id in (list or groups));

Of course, if you need more that userid, then you need a JOIN in first
two queries.

--
Milan Babuskov
http://swoes.blogspot.com/
http://www.flamerobin.org