一些sql查询来获取没有关系的数据

时间:2013-03-01 12:14:17

标签: mysql sql

有三个表'用户','组''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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'
                  )