如何从已与映射表连接的表中获取记录
以下示例:
用户表
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
请帮帮我..
答案 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 |
+----------+-------------+-------+