2014-03-06 176 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');