[英]Joining two tables on multiple values of the joining column
我陷入无法取得任何进展的境地。 要求如下。
我有两个表,一个是 ContentTag
Id ContentId TagId
1 48 3
2 48 4
3 48 5
4 48 6
5 47 7
6 47 8
9 47 1
10 47 2
这包含内容表和标签表之间的链接
并且有 foldettag 表,其中包含文件夹表和标签表之间的链接
Id FolderId TagId
2 2 3
3 2 4
4 2 5
5 2 6
6 4 3
7 5 1
8 5 2
9 5 3
10 10 1
该文件夹将仅包含链接到所有喜欢该文件夹的标签的内容。
注意:我需要的结果 whihc 包含那些链接到完全相同标签的 contentId 和 FolderId 的链接。
例如它将包含以下结果
ContentId FolderId
48 2
有人可以向我建议一些我应该遵循的方法来继续吗?
我试图在过去几个小时内找到解决方案,但找不到任何解决方案谢谢
在 SQL Server 2017 中,您可以使用STRING_AGG()
:
WITH
c AS (
SELECT ContentId, STRING_AGG(TagId, ',') WITHIN GROUP (ORDER BY TagId) tags
FROM ContentTag
GROUP BY ContentId
),
f AS (
SELECT FolderId, STRING_AGG(TagId, ',') WITHIN GROUP (ORDER BY TagId) tags
FROM FolderTag
GROUP BY FolderId
)
SELECT c.ContentId, f.FolderId
FROM c INNER JOIN f
ON f.tags = c.tags
请参阅演示。
结果:
> ContentId | FolderId
> --------: | -------:
> 48 | 2
如果您想要一个包含至少一个匹配标签的文件夹和所有内容的结果,那么join
就足够了:
select ft.folderid, ct.contentid
from foldertags ft join
contenttag ct
on ft.tagid = ct.tagid
declare @ContentTag table
(
Id int identity,
ContentId int,
TagId int
);
insert into @ContentTag(ContentId, TagId)
values
(48, 3), (48, 4), (48, 5), (48, 6),
(47, 7), (47, 8), (47, 1), (47, 2),
(46, 4), (46, 6);
declare @FolderTag table
(
Id int identity,
FolderId int,
TagId int
);
insert into @FolderTag(FolderId, TagId)
values
(2, 3), (2, 4), (2, 5), (2, 6),
(4, 3), (5, 1), (5, 2), (5, 3), (10, 1),
(11, 4), (11, 6);
select f.FolderId, c.ContentId
from
(
select FolderId, TagId, count(*) over(partition by FolderId) as FolderTagCount
from @FolderTag
) as f
join
(
select ContentId , TagId, count(*) over(partition by ContentId) as ContentTagCount
from @ContentTag
) as c on f.TagId = c.TagId and f.FolderTagCount = c.ContentTagCount
group by f.FolderId, c.ContentId
having count(f.TagId) = max(c.ContentTagCount);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.