[英]Joining two tables on multiple values of the joining column
I am stuck in situation where I am unable to make any progress.我陷入无法取得任何进展的境地。 The requirement is below.要求如下。
I have two tables one is ContentTag我有两个表,一个是 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
This contains the linking between Content table and tag table这包含内容表和标签表之间的链接
and there is foldettag table which contains the linking between folder table and tag table并且有 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
the folder will contain only those contents which are linked to all the tags which are liked to the folder.该文件夹将仅包含链接到所有喜欢该文件夹的标签的内容。
Note: I need the result whihc contains the link of those contentId and FolderId which are linked to exactly same tags.注意:我需要的结果 whihc 包含那些链接到完全相同标签的 contentId 和 FolderId 的链接。
for example it will contain the following result例如它将包含以下结果
ContentId FolderId
48 2
Can someone plz suggest to me some approach which I should follow to proceed with this?有人可以向我建议一些我应该遵循的方法来继续吗?
I am trying to find a solution for the past few hours but unable to find any solution Thank you我试图在过去几个小时内找到解决方案,但找不到任何解决方案谢谢
In SQL Server 2017 you can use STRING_AGG()
:在 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
See the demo .请参阅演示。
Results:结果:
> ContentId | FolderId
> --------: | -------:
> 48 | 2
If you want a result with the folder and all content that has at least one matching tag, then join
should suffice:如果您想要一个包含至少一个匹配标签的文件夹和所有内容的结果,那么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.