Compare text differences between two almost identical rows / tables in MySql

五迷三道 提交于 2019-12-14 02:51:21

问题


I have 2 identical tables with different set of data's, now I would like to compare the words in a single field against multiple rows of the same column in table b and let me know the percentage of matches against each id

Example:

The following are the entries in Table A

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

The following are the entries in Table B

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

The desired result

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.

It would be really great if someone could help me with the same.


回答1:


Although it would be easier to accomplish this in your application code, it is possible via a couple of MySQL functions:

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 ;

The first function is used in the second, which is the one you want to call in your code, like so:

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


来源:https://stackoverflow.com/questions/22223697/compare-text-differences-between-two-almost-identical-rows-tables-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!