Search code examples
sqlsql-serverleft-join

Join a table with another table with columns containing null


I want to join users table with both Groupid and superadmingroupid from group table. Superadmingroupid may be null

I tried below query but not working

SELECT U.Name, G.Name
FROM Groups G
INNER JOIN USERS U ON G.Groupid = U.Gid
LEFT JOIN USERs  U2 On G.superadmingroupid= U.Gid
where U.Name='Mishrsa'

Group table

 Groupid       Gname        SuperAdminGroupId  
    -----      ------          --------  
    17           A             3            
    
    2             B          null
    
    3             C          null 

        

Users
------
id       Name    Gid
--     -------   ----
1        mishra   2
2        mishrsa  3

I want to diplay the user with groups that are referenced as groupid or superadmingroupid Ex: User does not have groupid 17 but superadmingroupid 3 is there in users table so group 17 should come in the output

Output
Name          GName 
Mishra     B
Mishra      C
Mishra      A

Solution

  • Solution for your problem is:

    SELECT U.Name, G.GName
    FROM Groups G
    INNER JOIN USERS U 
    ON G.Groupid = U.Gid 
    OR G.superadmingroupid= U.Gid;
    

    Working example: dbfiddle Link