开发者

SQL Query to Show If Two Users in Same Group

开发者 https://www.devze.com 2022-12-09 09:36 出处:网络
I\'ve got a database with 3 tables: users, groups, and groupmembers. users: id int username varchar(50) groups:

I've got a database with 3 tables: users, groups, and groupmembers.

users:
id int
username varchar(50)

groups:
id int
name varchar(50)

groupmembers:
id int
groupid int
user int

Given two user ids, how can I use one query to determine if they share membership in any group (not any particular one, but any group). I'd开发者_开发百科 like the query to return null if they share no membership and not null if they do share membership.


Alternately

select count(*) from groupmembers 
  where user=@user1 
    and groupid in 
      (select groupid from groupmembers where user=@user2)

That will return a count of groups in common. You can test for the count by replacing count*) with the following:

IF(count(*)>0,1,Null)


Here's a SQL that will return the groups that both users are a member of

SELECT g1.id
FROM groupmembers g1 join groupmembers g2 on g1.id = g2.id
WHERE g1.user = @user1
AND g2.user = @user2;

If want to just return '1' or 'Null' you could wrap this as follows

With groupcount as (
    SELECT count(*) gc
    FROM groupmembers g1 join groupmembers g2 on g1.id = g2.id
    WHERE g1.user = @user1
    AND g2.user = @user2)
SELECT Case When gc = 0 Then Null Else 1 End as SharedGroups
FROM groupcount;
0

精彩评论

暂无评论...
验证码 换一张
取 消