好的,其中 ADVERTFACETTERMASSIGNMENT 是 {AdvertId, FacetTermId} 用于两个词搜索...
select fta1.AdvertID
from ADVERTFACETTERMASSIGNMENT fta1
join ADVERTFACETTERMASSIGNMENT fta2 on fta1.AdvertID = fta2.AdvertID
where fta1.FacetTermId = @searchFacet1 and fta2.FacetTermID = @searchFacet2
and fta1.AdvertID <> @searchAdvertId
工作示例的一般答案:
declare @AdvertFacetTermAssignment table (AdvertId int, FacetTermId int)
insert into @AdvertFacetTermAssignment values
(1,10), (1,11), (2,10), (3,11), (4,10), (4,11), (5,10), (5,11), (5,12), (6,10), (6,12), (6,13), (7, 10), (7, 11), (8, 12), (9,10), (9,11), (9,12), (10, 10), (10,12)
declare @searchAdvertId int = 1
declare @targetMatch int = (select COUNT(*) from @AdvertFacetTermAssignment where AdvertId = @searchAdvertId)
select aft2.AdvertId from @AdvertFacetTermAssignment aft1
join @AdvertFacetTermAssignment aft2
on aft1.FacetTermId = aft2.FacetTermId and aft1.AdvertId <> aft2.AdvertId
where aft1.AdvertId = @searchAdvertId
group by aft2.AdvertId
having COUNT(*) = @targetMatch
结果 = 4,5,7,9
最后一个不是所要求的,而是抓取所有相似的东西(一些匹配的方面)并按相似程度排序。
(所有比赛一视同仁)
select aft2.AdvertId, COUNT(aft1.AdvertId) as matches, ABS(COUNT(*)-@targetMatch) as nonMatches
from @AdvertFacetTermAssignment aft1
right outer join @AdvertFacetTermAssignment aft2
on aft2.FacetTermId = aft1.FacetTermId
and aft1.AdvertId = @searchAdvertId
and aft2.AdvertId <> @searchAdvertId
group by aft2.AdvertId
having COUNT(aft1.AdvertId) > 0
order by COUNT(aft1.AdvertId) DESC, ABS(COUNT(*)-@targetMatch) ASC
结果:
AdvertId matches nonMatches
4 2 0
7 2 0
9 2 1
5 2 1
10 1 0
6 1 1
2 1 1
3 1 1
(顺便说一句,我是从威斯康星州苏塞克斯发布的)