SQL - 如何将两个表与第三个表链接并获取所有记录

时间:2012-01-12 19:42:08

标签: sql-server-2008

好的,所以这些是我的三张桌子:

用户

|--------+----------+----------|
| UserID | UserName | IsActive |
|--------+----------+----------|
|   10   |   Mike   |     1    |
|   11   |   John   |     1    |
|   12   |   Beth   |     1    |
|--------+----------+----------|

REPORT_DISTRIB (链接表)

|-----------+--------+----------+---------------|
| DistribID | UserID | ReportID | DistribToUser |
|-----------+--------+----------+---------------|
|     1     |   10   |    50    |       1       |
|     2     |   12   |    52    |       0       |
|     3     |   14   |    54    |       1       |
|-----------+--------+----------+---------------|

报告

|----------+------------+---------------|
| ReportID | ReportName | Distributable |
|----------+------------+---------------|
|    50    |   FY2010   |       1       |
|    51    |   FY2011   |       1       |
|    52    |   FY2012   |       1       |
|----------+------------+---------------|

在我面临的问题中,我有来自USER表的200个活跃用户和来自REPORT表的10个可分发的用户。对于每个用户,我需要显示用户名,报告名称以及是否应将该报告分发给用户,如下所示:

|----------+------------+---------------|
| UserName | ReportName | DistribToUser |
|----------+------------+---------------|
|   Mike   |   FY2010   |       1       |
|   Beth   |   FY2012   |       0       |
|----------+------------+---------------|

我想要实现的是2000个结果列表(200个用户x 10个报告)。问题是REPORT_DISTRIB链接表没有每个报告的每个用户的记录。我仍觉得这应该是可能的......我的思维错了吗?非常感谢任何帮助。

这很粗糙,但到目前为止这是我的查询(返回1790结果):

SELECT u.UserName, r.ReportName, rd.DistribToUser
FROM USER u
LEFT JOIN REPORT_DISTRIB rd on rd.UserID = u.UserID
  and rd.ReportID in (select r.ReportID from REPORT r where r.Distributable = 1)
OUTER APPLY (select r.ReportName from REPORT r where r.ReportID = rd.ReportID) r
WHERE u.IsActive = 1

1 个答案:

答案 0 :(得分:3)

SELECT u.UserName, r.ReportName, COALESCE(rd.DistribToUser, 0)
    FROM USER u
        CROSS JOIN REPORT r
        LEFT JOIN REPORT_DISTRIB rd
            ON u.UserID = rd.UserID
                AND r.ReportID = rd.ReportID
    WHERE u.IsActive = 1
        AND r.Distributable = 1