用戶與角色是多對多的關係,
一個角色能夠被賦予給多個用戶,一個用戶也能夠擁有多個角色;
查詢不擁有某角色的全部用戶,
若是用leftjoin查詢,會形成重複的記錄:
舉例錯誤的作法:spa
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爲其餘值)
那麼這個查詢中會查出該用戶,
違背了咱們的需求;
正確的作法是:code
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)查詢要快的多!
it