简体   繁体   中英

SQL statement left join where children is null or

I have two tables 'user_rights' as parent table and 'assigned_rights' as child. I need to show all rights which has no child in table 'assigned_rights' and if there is a child I have to check if one of the child's is not equel to a user_id.

   SELECT   ur.right_id, 
      ur.right_name, 
      ur.right_description, 
      ur.right_level, 
      ura.user_id
   from user_rights  as ur
   left join assigned_rights as ura
   on ur.right_id = ura.right_id
   where ura.user_id is null or ura.user_id <> 'abc'

My select works fine when there are no childs and also if there is a child and userid match field 'user_id'. Problem is, if there are childs with different user id's.

If you want the child related use inner join

 SELECT   ur.right_id, 
      ur.right_name, 
      ur.right_description, 
      ur.right_level, 
      ura.user_id
   from user_rights  as ur
   inner join join assigned_rights as ura
   on ur.right_id = ura.right_id
   where ura.user_id <> 'abc'

SELECT ur.right_id, ur.right_name, ur.right_description, ur.right_level, ura.user_id from user_rights as ur left join assigned_rights as ura on ur.right_id = ura.right_id and ura.user_id = 'abc'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM