且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较MySql中两个几乎相同的行/表之间的文本差异

更新时间:2022-11-17 17:09:51

尽管在应用程序代码中完成此操作会更容易,但是可以通过以下几个MySQL函数来实现:

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');