前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在【用户、角色、权限】模块中如何查询不拥有某角色的用户

在【用户、角色、权限】模块中如何查询不拥有某角色的用户

作者头像
liulun
发布2019-07-19 16:46:19
2.6K0
发布2019-07-19 16:46:19
举报
文章被收录于专栏:liulunliulunliulun

用户与角色是多对多的关系, 一个角色可以被赋予给多个用户,一个用户也可以拥有多个角色; 查询不拥有某角色的所有用户, 如果用leftjoin查询,会造成重复的记录: 举例错误的做法:

select * from `system_user` 
left join `system_user_role` on `system_user`.`id` = `system_user_role`.`user_id` 
where not `system_user_role`.`role_id` = '6ce3c030-a2e0-11e9-8bdc-495ad65d4804' 
or `system_user_role`.`role_id` is null 
order by `system_user_role`.`create_time` desc limit 38;

这个查询虽然用到了(or `system_user_role`.`role_id` is null )防止结果缺失,但会有重复的记录出现! 如果一个用户, 被赋予了角色(id为6ce3c030-a2e0-11e9-8bdc-495ad65d4804) 该用户又被赋予了另一个角色(id为其他值) 那么这个查询中会查出该用户, 违背了我们的需求; 正确的做法是:

select * from `system_user` 
where not exists (select 1 from `system_user_role` where system_user.id = system_user_role.user_id and system_user_role.role_id = '6ce3c030-a2e0-11e9-8bdc-495ad65d4804' );

这个做法用到了not exists子查询 注意:这样的子查询是可以设置与父查询的关联条件的(where system_user.id = system_user_role.user_id) 这种查询比(not in)查询要快的多!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档