如何在mysql中使用levenshtein函数查找标题相似的文章

ttygqcqt  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(305)

所以我希望能够找到类似的文章,根据他们的标题,我发现了关于莱文施坦。我将在下面发布函数。所以我的问题是,如何使用这个函数?我认为这只是为了找到单字,但在我的情况下,我需要它找到整个句子的形式标题。莱文斯坦是我需要的东西吗?如果值得一提的话,我的网站是用php开发的。也许你可以推荐一些php库。

BEGIN
DECLARE s1_len, s2_len, i, j, c, c_temp, cost INT;
DECLARE s1_char CHAR;
-- max strlen=255
DECLARE cv0, cv1 VARBINARY(256);
SET s1_len = CHAR_LENGTH(s1), s2_len = CHAR_LENGTH(s2), cv1 = 0x00, j = 1, i = 1, c = 0;
IF s1 = s2 THEN
RETURN 0;
ELSEIF s1_len = 0 THEN
RETURN s2_len;
ELSEIF s2_len = 0 THEN
RETURN s1_len;
ELSE
WHILE j <= s2_len DO
SET cv1 = CONCAT(cv1, UNHEX(HEX(j))), j = j + 1;
END WHILE;
WHILE i <= s1_len DO
SET s1_char = SUBSTRING(s1, i, 1), c = i, cv0 = UNHEX(HEX(i)), j = 1;
WHILE j <= s2_len DO
SET c = c + 1;
IF s1_char = SUBSTRING(s2, j, 1) THEN
SET cost = 0; ELSE SET cost = 1;
END IF;
SET c_temp = CONV(HEX(SUBSTRING(cv1, j, 1)), 16, 10) + cost;
IF c > c_temp THEN SET c = c_temp; END IF;
SET c_temp = CONV(HEX(SUBSTRING(cv1, j+1, 1)), 16, 10) + 1;
IF c > c_temp THEN
SET c = c_temp;
END IF;
SET cv0 = CONCAT(cv0, UNHEX(HEX(c))), j = j + 1;
END WHILE;
SET cv1 = cv0, i = i + 1;
END WHILE;
END IF;
RETURN c;
END
fslejnso

fslejnso1#

对于一个大表来说,这将是非常昂贵的,但是您可以自联接该表以查找类似的标题:

SELECT t2.id, t2.title
FROM yourTable AS t1
JOIN yourTable AS t2 ON t1.id != t2.id AND levenshtein(t1.title, t2.title) < 10
WHERE t1.id = :selected_id

替换 10 随着标题之间的距离越来越近——数字越小就越近。

相关问题