大家好,我可以重写查询:
select userid from User where userid not in(select userid from UserRole where roleid in(8));
作为加入?
问题是一个用户可能有多个角色 先感谢您。
mysql> desc User; +--------------------+-------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+-------------------+------+-----+---------+----------------+ | userId | int(11) | NO | PRI | NULL | auto_increment | | userName | varchar(50) | YES | | NULL | |
...和其他用户相关的列
mysql> desc UserRole; +--------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+---------+------+-----+---------+-------+ | userId | int(11) | NO | PRI | 0 | | | roleId | int(11) | NO | PRI | 0 | | +--------+---------+------+-----+---------+-------+
答案 0 :(得分:1)
我没有对此进行测试,但我认为它有效。
select userID from user
left join UserRole
on user.userID = UserRole.userID
and UserRole.roleID = 8
where UserRole.roleID IS NULL
答案 1 :(得分:0)
也许这会有用吗?
select userid from User
left outer join
(select userid, roleid from UserRole where roleid in(8)) v
on User.userid = v.userid
where roleid is null;
答案 2 :(得分:0)
我认为这应该可以让你拥有8个以外角色的每个人
select userid from User
where not exists
(select UserId from UserRole
where UserRole.userid = User.userid and roleid not in(8) )
答案 3 :(得分:0)
如果您想要提高可读性,可以使用EXCEPT子句。
即
select userId from user
except
select userId from UserRole where roleId <> 8
不确定MySQL是否支持“除外”。