如何从SQL Server中与映射表连接的表中获取记录

时间:2017-06-07 16:05:05

标签: sql-server sql-server-2008-r2

如何从已与映射表连接的表中获取记录

以下示例:

用户

ID | Name
---+-------
1  | ABC
2  | xyz
3  | NYS

功能

ID | Name
---+------
1  | F1
2  | F2
3  | F3
4  | F4

映射

ID  |  UserID | FeatureID
----+---------+----------
1   |    1    |    1
2   |    1    |    2
3   |    2    |    2
4   |    3    |    1

我需要结果如下:

UserName | FeatureName |  IsMap 
---------+-------------+------------
ABC      |    F1       |   True
ABC      |    F2       |   True
ABC      |    F3       |   False
ABC      |    F4       |   False
XYZ      |    F1       |   False
XYZ      |    F2       |   True 
XYZ      |    F3       |   False
XYZ      |    F4       |   False
NYS      |    F1       |   True 
NYS      |    F2       |   False
NYS      |    F3       |   False
NYS      |    F4       |   False

请帮帮我..

1 个答案:

答案 0 :(得分:0)

首先cross join将您的User数据发送到Feature数据,以获取所有组合。然后,您可以left join将此Mapping表格检查是否存在映射。如果这返回null值,则表示您没有匹配项,您可以使用case表达式处理该匹配项:

declare @User table(ID int,Name nvarchar(100));
insert into @User values (1,'ABC'),(2,'xyz'),(3,'NYS');

declare @Feature table(ID int,Name nvarchar(100));
insert into @Feature values (1,'F1'),(2,'F2'),(3,'F3'),(4,'F4');

declare @Mapping table(ID int,UserID int,FeatureID int);
insert into @Mapping values (1,1,1),(2,1,2),(3,2,2),(4,3,1);

select u.Name as UserName
        ,f.Name as FeatureName
        ,case when m.ID is not null then 'True' else 'False' end as IsMap
from @User u
    cross join @Feature f
    left join @Mapping m
        on(u.ID = m.UserID
            and f.ID = m.FeatureID
            )
order by u.Name
        ,f.Name;

输出:

+----------+-------------+-------+
| UserName | FeatureName | IsMap |
+----------+-------------+-------+
| ABC      | F1          | True  |
| ABC      | F2          | True  |
| ABC      | F3          | False |
| ABC      | F4          | False |
| NYS      | F1          | True  |
| NYS      | F2          | False |
| NYS      | F3          | False |
| NYS      | F4          | False |
| xyz      | F1          | False |
| xyz      | F2          | True  |
| xyz      | F3          | False |
| xyz      | F4          | False |
+----------+-------------+-------+