mysql存储函数用于在查询中进行多次替换

发布于 2024-12-09 16:49:11 字数 783 浏览 0 评论 0原文

我有一个 table1

tid letter1 letter2
1   a       e
2   p       b
3   c       k
4   pp      bb
5   rr      ll

和另一个 table2

t2id word
1    banana
2    strawberry
3    apple
4    grape

我需要一个 mysql 函数来在 table1 上进行替换过程后将输入单词与 table2 中的单词进行比较,例如:

SELECT CHAR_LENGTH(word) AS charl FROM table2;

DECLARE i INT DEFAULT 0;

SET query = CONCAT(
    ' SELECT word FROM table2 WHERE ( ',
    WHILE i < charl DO 
        //if word's i'nth letter found in the table1
        IF (SELECT letter2 FROM table1 WHERE word{i} = letter1)
        //replace letter1 with letter2 on this row
        'REPLACE(word,letter1,letter2) AND ', 
    END;
    ' ) = 'inputword' ';

我的 mysql 知识很差,无法做到这一点。我该怎么做?

i have one table1

tid letter1 letter2
1   a       e
2   p       b
3   c       k
4   pp      bb
5   rr      ll

and another table2

t2id word
1    banana
2    strawberry
3    apple
4    grape

i need a mysql function to compare an input word with words from table2 after a replacing process on table1, like:

SELECT CHAR_LENGTH(word) AS charl FROM table2;

DECLARE i INT DEFAULT 0;

SET query = CONCAT(
    ' SELECT word FROM table2 WHERE ( ',
    WHILE i < charl DO 
        //if word's i'nth letter found in the table1
        IF (SELECT letter2 FROM table1 WHERE word{i} = letter1)
        //replace letter1 with letter2 on this row
        'REPLACE(word,letter1,letter2) AND ', 
    END;
    ' ) = 'inputword' ';

my mysql knowledgeis so poor to do this. how can i do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森林散布 2024-12-16 16:49:11

正如您所猜测的,您需要在存储过程中执行此操作。

实际上是一个存储函数:

DELIMITER $

CREATE FUNCTION ReplaceChars(Fullword VARCHAR(255)
                           , ReplaceThis VARCHAR(255) 
                           , WithThis VARCHAR(255) ) RETURNS VARCHAR(255)
BEGIN
  DECLARE Result VARCHAR(255);
  DECLARE i INTEGER;     

  SET Result = Fullword;
  IF LENGTH(ReplaceThis) = LENGTH(WithThis) THEN 
    SET i = LENGTH(ReplaceThis);
    WHILE i > 0 DO
      SET Result = REPLACE(Result, MID(ReplaceThis,i,1),MID(WithThis,i,1));
      SET i = i - 1;
    END WHILE;
  END IF;
  RETURN Result;
END $

As you guessed you need to do this in a stored procedure.

Actually a stored function:

DELIMITER $

CREATE FUNCTION ReplaceChars(Fullword VARCHAR(255)
                           , ReplaceThis VARCHAR(255) 
                           , WithThis VARCHAR(255) ) RETURNS VARCHAR(255)
BEGIN
  DECLARE Result VARCHAR(255);
  DECLARE i INTEGER;     

  SET Result = Fullword;
  IF LENGTH(ReplaceThis) = LENGTH(WithThis) THEN 
    SET i = LENGTH(ReplaceThis);
    WHILE i > 0 DO
      SET Result = REPLACE(Result, MID(ReplaceThis,i,1),MID(WithThis,i,1));
      SET i = i - 1;
    END WHILE;
  END IF;
  RETURN Result;
END $
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文