自定义函数查找相似
和计算相似度
问
描述:
结构如下
ShopID Tag TagType
--------------------------------------
1 手抓肉 烤肉 抓饭 拉条子 2 2 烤肉 抓饭 拉条子 2
3 手抓肉 抓饭 拉条子 2
4 手抓肉 烤肉 抓饭 2
5 囊坑肉 大盘鸡 抓饭 拉条子 2 6 拌面 烤肉 抓饭 拉条子 2 7 手抓肉 大盘鸡 抓饭 拉条子 2
需要搜索与提供的Tag内容(如手抓肉 烤肉 抓饭)相似的记录,并按照相似度从高到低排
列,其中Tag是以空格分割的,如上的内容就是说Tag包含手抓肉,烤肉,抓饭,而其他数
据只要包含其中一条就表示他们相似,包含的越多就表示越相似。
用自定义函数查找记录和计算相似度,查询时按相似度排序,相似度的定义是,与提供的
Tag中的一项相符的就加1,以最后的和来表示相似度。
--建立环境
create table test1289(
ShopID int,
Tag nvarchar(50),
TagType int
)
insert test1289 select
--------------------------------------
1, N'手抓肉 烤肉 抓饭 拉条子' , 2 union all select
2, N'烤肉 抓饭 拉条子' , 2
union all select
3, N'手抓肉 抓饭 拉条子' , 2 union all select
4, N'手抓肉 烤肉 抓饭' , 2
union all select
5, N'囊坑肉 大盘鸡 抓饭 拉条子' , 2 union all select
6, N'拌面 烤肉 抓饭 拉条子' , 2 union all select
7, N'手抓肉 大盘鸡 抓饭 拉条子' , 2
go
--函数
alter function fn_相似记录( @Tag nvarchar(50)
)
returns @r table ( --返回表
ShopID int,
Tag nvarchar(50),
TagType int,
相似度 int
)
as
begin
declare @t nvarchar(50) --存放中间字符串
while charindex(' ',@Tag)>0 --以空格分隔,循环找
没一个项
begin
set @t=left(@Tag,charindex(' ',@Tag)-1) --取出中间字符串
set @Tag=stuff(@Tag,1,charindex(' ',@Tag),'') --往后移
update @r
--已经有的记录相似度加1
set 相似度=相似度+1
where ' '+Tag+' ' like '% '+@t+' %'
insert @r select t.*,1 --
没有的记录添加,相似度为1
from test1289 t
where ' '+Tag+' ' like '% '+@t+' %'
and not exists ( select 1 from @r where ShopId=t.ShopId)
end
if @Tag<>''
--最后一个项
begin
set @t=@Tag
update @r
--已经有的记录相似度加1
set 相似度=相似度+1
where ' '+Tag+' ' like '% '+@t+' %'
insert @r select t.*,1
--没有的记录添加,相似度为1
from test1289 t
where ' '+Tag+' ' like '% '+@t+' %'
and not exists ( select 1 from @r where ShopId=t.ShopId)
end
return
end
go
--测试调用
select * from fn_相似记录(N'手抓肉 烤肉 抓饭') order by 相似度 desc
go
--结果
ShopID Tag TagType 相
似度
----------- -------------------------------------------------- ----------- -----------
4 手抓肉 烤肉 抓饭 2 3
1 手抓肉 烤肉 抓饭 拉条子 2 3
3 手抓肉 抓饭 拉条子 2 2
7 手抓肉 大盘鸡 抓饭 拉条子 2 2
2 烤肉 抓饭 拉条子 2 2
6 拌面 烤肉 抓饭 拉条子 2 2
5 囊坑肉 大盘鸡 抓饭 拉条子 2 1
(所影响的行数为 7 行)
--删除环境
drop function fn_相似记录
drop table test1289