总而言之,今天我在处理充满词汇的 MySQL 表时遇到了一些麻烦。我需要能够快速检索具有相同辅音和元音排列的单词,所以我的想法是按照这些大约 30 万行的结构进行构建:
CREATE TABLE words(
`value` VARCHAR(100),
`pattern` VARCHAR(100)
);
填充一小部分内容:
INSERT INTO words(`value`) VALUES
('aardvark'),
('aardvarks'),
('aardwolf'),
('aardwolves'),
#...
('mortal'),
('mortals'),
#...
('posted'),
('posteen'),
#...
('zymotoxic'),
('zymurgies');
以下查询应返回“mortal”和“posted”:
SELECT `value` FROM words WHERE `pattern` = '101101';
因为'1'代表辅音而'0'代表元音。我知道 MySQL 没有 regexp_replace 等效项,所以我想知道填充该pattern
字段的最佳方法是什么?我假设它不是慢得令人遗憾:
UPDATE words SET `pattern` = REPLACE(`value`, 'a', '0');
UPDATE words SET `pattern` = REPLACE(`pattern`, 'b', '1');
UPDATE words SET `pattern` = REPLACE(`pattern`, 'c', '1');
UPDATE words SET `pattern` = REPLACE(`pattern`, 'd', '1');
UPDATE words SET `pattern` = REPLACE(`pattern`, 'e', '0');
#...
UPDATE words SET `pattern` = REPLACE(`pattern`, 'z', '1');
目前正在尝试使用游标循环遍历单词表并逐个更新每个模式的存储过程,但是,也许不足为奇,这并不快。我错过了一些非常明显的东西吗?
提前感谢您能给我的任何帮助。
编辑:添加了存储过程方法。这速度更快但幅度不大(每千行 0.7 秒,累加起来)但它完成了工作。
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `set_word_pattern`()
BEGIN
DECLARE l_last_row INT DEFAULT 0;
DECLARE temp_word VARCHAR(100);
#DECLARE temp_char CHAR(1);
DECLARE temp_pattern_word VARCHAR(100);
DECLARE c_traverse_words CURSOR FOR SELECT `value` FROM words WHERE pattern = "" LIMIT 20000;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET l_last_row = 1;
OPEN c_traverse_words;
cursor_loop: LOOP
FETCH c_traverse_words INTO temp_word;
IF l_last_row = 1 THEN
LEAVE cursor_loop;
END IF;
SET temp_pattern_word = get_pattern(temp_word);
UPDATE words SET `pattern` = temp_pattern_word WHERE `value` = temp_word;
END LOOP cursor_loop;
CLOSE c_traverse_words;
SELECT "Done"; #temp_pattern_word;
END
以及它调用的函数:
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `get_pattern`(new_word VARCHAR(100)) RETURNS varchar(100) CHARSET utf8
BEGIN
DECLARE temp_char CHAR(1);
DECLARE temp_pattern_word VARCHAR(100);
DECLARE i INT;
SET temp_pattern_word = "";
SET i = 1;
WHILE(i <= CHAR_LENGTH(new_word)) DO
SET temp_char = MID(new_word, i, 1);
IF temp_char IN ("a", "e", "i", "o", "u") THEN
SET temp_pattern_word = CONCAT(temp_pattern_word, "0");
ELSE
SET temp_pattern_word = CONCAT(temp_pattern_word, "1");
END IF;
SET i = i + 1;
END WHILE;
RETURN temp_pattern_word;
END