2014-03-06 174 views
0

我有两个具有不同数据集的相同表,现在我想比较单个字段中的单词与表b中同一列的多行,并让我知道比赛的针对每个ID的百分比比较mysql中两个相同表之间的行之间的差异

实施例:

以下是表A中的条目

Row1: 1, salt water masala 
Row2: 2, water onion maggi milk 

以下是表B

中的条目
Row1: 1, salt masala water 
Row2: 2, water onion maggi 

期望的结果

Row1: Match 100% (All the 3 words are available but different order) 
Row2: Match 75% as 1 word does not match out of the 4 words. 

这将是真正伟大的,如果有人可以帮助我一样。

+0

不适用于SQL。为此使用应用程序。 (至少对于你的评论,对于有'MATCH..AGAINST'构造的百分比,需要'FULLTEXT') –

回答

0

虽然它会更容易在应用程序代码来实现这一点,通过一对夫妇的MySQL的功能是可能的:

delimiter // 

drop function if exists string_splitter // 
create function string_splitter(
    str text, 
    delim varchar(25), 
    pos tinyint) returns text 
begin 
return replace(substring_index(str, delim, pos), concat(substring_index(str, delim, pos - 1), delim), ''); 
end // 

drop function if exists percentage_of_matches // 

create function percentage_of_matches(
    str1 text, 
    str2 text)returns double 
begin 
set str1 = trim(str1); 
set str2 = trim(str2); 
while instr(str1, ' ') do 
    set str1 = replace(str1, ' ', ' '); 
end while; 
while instr(str2, ' ') do 
    set str2 = replace(str2, ' ', ' '); 
end while; 
set @i = 1; 
set @numWords = 1 + length(str1) - length(replace(str1, ' ', '')); 
set @numMatches = 0; 
while @i <= @numWords do 
    set @word = string_splitter(str1, ' ', @i); 
    if str2 = @word or str2 like concat(@word, ' %') or str2 like concat('% ', @word) or str2 like concat('% ', @word, ' %') then 
    set @numMatches = @numMatches + 1; 
    end if; 
    set @i = @i + 1; 
end while; 
return (@numMatches/@numWords) * 100; 
end // 

delimiter ; 

第一个功能是在第二,这是你想要的一个使用请拨打您的代码,如下所示:

select percentage_of_matches('salt water masala', 'salt masala water'); 
select percentage_of_matches('water onion maggi milk', 'water onion maggi');