简体   繁体   English

JOIN仅适用于一张桌子吗?

[英]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: 我想出了下面的SQL代码:

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. 在我看来, JOIN工作方式是选择一个表并将其链接到其他表。 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. 我在第三栏中使用SELECT语句解决了这个问题。 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. 它不会让我ORDER BY Project ,这是我拥有该列的别名。

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. 左联接与普通(INNER)联接具有相同的功能,但是如果没有匹配项,它将仍然拉入父记录。

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;  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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