如何区分SQL查询但仍返回所有列

时间:2016-02-01 12:03:10

标签: sql sql-server

这是我的疑问:

SELECT dbo.Webs.Id, dbo.Webs.Title, dbo.Webs.FullUrl, dbo.Roles.RoleId,
       dbo.Roles.Title AS RoleTitle, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Login
FROM dbo.RoleAssignment
  INNER JOIN dbo.Roles ON dbo.RoleAssignment.SiteId = dbo.Roles.SiteId
                      AND dbo.RoleAssignment.RoleId = dbo.Roles.RoleId
  INNER JOIN dbo.Webs ON dbo.Roles.SiteId = dbo.Webs.SiteId
                     AND dbo.Roles.WebId = dbo.Webs.Id
  INNER JOIN dbo.UserInfo ON dbo.RoleAssignment.PrincipalId = dbo.UserInfo.tp_ID
WHERE tp_Title = 'HOBSON, Will';

此数据库包含所有sharepoint站点用户的所有权限。我正在尝试创建一个显示用户有权访问的所有网站的查询。目前它输出了大量重复信息。我只希望它显示具有不同角色标题或不同Web ID的结果。

query results

例如,在此查询中,我只想看到4个结果; 1,5,11和13.

(所有这些信息都在外部无法访问的本地测试SharePoint安装上,所以我在这里提供的唯一信息就是我的名字:))

2 个答案:

答案 0 :(得分:3)

使用表别名更容易阅读您的查询。您问题的直接答案是使用SELECT DISTINCT

SELECT DISTINCT w.Id, w.Title, w.FullUrl, r.RoleId, r.Title AS RoleTitle,
       ui.tp_Title, ui.tp_Login
FROM dbo.RoleAssignment ra INNER JOIN
     dbo.Roles r
     ON ra.SiteId = r.SiteId AND
        ra.RoleId = r.RoleId INNER JOIN
     dbo.Webs w
     ON r.SiteId = w.SiteId AND
        r.WebId = w.Id INNER JOIN
     dbo.UserInfo ui
     ON ra.PrincipalId = ui.tp_ID
WHERE tp_Title = 'HOBSON, Will';

但是,找到重复的原因会更好。像这样的重复通常是由不完整的连接条件引起的。修复连接是更好的方法,但有时需要SELECT DISTINCT

答案 1 :(得分:0)

您只需在查询中添加DISTINCT

SELECT DISTINCT dbo.Webs.Id, dbo.Webs.Title, dbo.Webs.FullUrl, dbo.Roles.RoleId,
       dbo.Roles.Title AS RoleTitle, dbo.UserInfo.tp_Title, dbo.UserInfo.tp_Login
FROM dbo.RoleAssignment
  INNER JOIN dbo.Roles ON dbo.RoleAssignment.SiteId = dbo.Roles.SiteId
                      AND dbo.RoleAssignment.RoleId = dbo.Roles.RoleId
  INNER JOIN dbo.Webs ON dbo.Roles.SiteId = dbo.Webs.SiteId
                     AND dbo.Roles.WebId = dbo.Webs.Id
  INNER JOIN dbo.UserInfo ON dbo.RoleAssignment.PrincipalId = dbo.UserInfo.tp_ID
WHERE tp_Title = 'HOBSON, Will';