-1

有三个表'users','groups''users_groups'用户和组表之间的关系是多对多的,users_groups 存储该关系。

 users        users_groups                             groups
 -id (pk)     -user_id(fk references users)            -id (pk)
 -username    -group_id (fk references groups)         -name
 -password 

数据:

users
1. abc
2. admin
3. user
4. tester

Groups
1. testgroup
2. newgroup

Users_groups
group_id    user_id
   1           1
   1           2

假设我们在第 1 组(测试组)页面上。我想获取所有不属于该组的用户。我怎样才能做到这一点?如果可能的话,我想用一个 sql 查询来执行这个

更新

SELECT u.username, g.name
FROM users u
LEFT JOIN groups_users ug ON u.id = ug.user_id
LEFT JOIN groups g ON g.id = ug.group_id
WHERE g.id !=1 OR g.id IS NULL
4

2 回答 2

0
SELECT u.username FROM
users u
LEFT JOIN
    users_groups ug ON u.id = ug.user_id,
    groups g ON g.group_id = ug.group_id

WHERE g.name != 'testgroup'
GROUP BY u.username
于 2013-03-01T12:20:05.377 回答
0

这是一个简单的查询:

select u.*
from users u
where u.id not in (select user_id from user_groups ug where group_id = 1)

如果您想按名称而不是编号引用:

select u.*
from users u
where u.id not in (select user_id
                   from user_groups ug join
                        groups g
                        on ug.group_id = g.id
                   where g.name = 'testgroup'
                  )
于 2013-03-01T14:11:50.183 回答