mysql - 将子查询(不在)重写为Join

标签 mysql

大家好,是否可以重写查询:

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       |       |  
+--------+---------+------+-----+---------+-------+  

最佳答案

我还没有测试过这个,但我认为它有效。

select userID from user 
left join UserRole 
on user.userID = UserRole.userID 
and UserRole.roleID = 8
where UserRole.roleID IS NULL

关于mysql - 将子查询(不在)重写为Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/412777/

相关文章:

mysql - 根据重复列返回值

android - 如何绘制从当前位置到从 Mysql 数据库检索到的位置的路径

mysql - 将两个表中的两个查询合并为一个结构

mysql - RSS 到数据库 - 如何插入带有任意字符的字符串?

php - CakePHP 的模型关联

mysql - 如何在 Orchard CMS 1.3.10 中使用 MySQL 数据库?

php - foreach 给我同一行四次(PHP、Active Record、CodeIgniter)

php - MySQL INSERT 查询无输出

jquery - 数据库查询中如何进行数学运算?

mysql - Propel 1.6 如何在 symfony2 中自动生成 Base/Peer/Query 模型类