简体   繁体   中英

JOIN applies to only one table?

I'm trying to compile user project permissions from three tables. I came up with the below SQL code:

SELECT U.UserName,
       G.Name,
       (SELECT PROJ.Name
        FROM [test 2].dbo.Projects as PROJ
        WHERE PROJ.ProjectID = PERM.ProjectID) AS Project

FROM [test 2].dbo.tbl_Sp_Users AS U
JOIN [test 2].dbo.tbl_Sp_UserGrps AS G
ON U.DefGroupID=G.ID

JOIN [test 2].dbo.tbl_ss_Permission_Project AS PERM
ON U.ID = PERM.UserID

ORDER BY U.UserName ASC;  

It seems to me that the way JOIN works is by picking one table and linking it to other tables. But what do I need to do if my main table doesn't have a direct link? I went around it by using a SELECT statement in my third column. Is that the best way to do it ?

Finally, another related simple question. How can I sort by the third column? It wouldn't let me ORDER BY Project which is the alias I have the column.

Looks like you want a LEFT JOIN. A left join does the same thing as an ordinary (INNER) join, but if if there is no match, it will still pull in the parent records.

Try this:

SELECT 
  U.UserName
 ,G.Name
 ,proj.name
FROM
  [test 2].dbo.tbl_Sp_Users U
  inner JOIN [test 2].dbo.tbl_Sp_UserGrps G ON U.DefGroupID=G.ID
  inner JOIN [test 2].dbo.tbl_ss_Permission_Project PERM ON U.ID = PERM.UserID
  left join [test_2].dbo.Projects proj ON proj.projectid = PERM.projectid
ORDER BY
  U.UserName ASC;  
SELECT U.UserName,
       G.Name,
        PROJ.Name
FROM [test 2].dbo.tbl_Sp_Users AS U
JOIN [test 2].dbo.tbl_Sp_UserGrps AS G
    ON U.DefGroupID=G.ID
JOIN [test 2].dbo.tbl_ss_Permission_Project AS PERM
    ON U.ID = PERM.UserID
LEFT JOIN [test 2].dbo.Projects AS PROJ 
    ON  PROJ.ProjectID = PERM.ProjectID
ORDER BY U.UserName ASC;  

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