Mysql

如何使用查詢結果作為 REPLACE 參數

  • August 1, 2019

我試圖:

1- 在大量內容中查找字元串

2-使用 REPLACE 函式將字元串的特定部分替換為新部分,如下所示:

REPLACE(column_name, query#1, query#2)

這可能嗎?

我已經找到要替換的內容的確切部分

SELECT `post_title`, SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) AS amazonlinks FROM wp_posts_duplicatedfortestonly WHERE `post_content` LIKE '%[flv:%'

並在另一個表列中準備好新字元串:Png_Link

最後,我嘗試使用 REPLACE 函式合併所有這些,但它給了我很多錯誤:

UPDATE wp_posts_duplicatedfortestonly 
SET 
   post_content = REPLACE(post_content,
                          (SELECT SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) FROM (SELECT post_content FROM wp_posts_duplicatedfortestonly) AS something WHERE `post_content` LIKE '%[flv:%'),
                          (SELECT `Png_Link`  FROM `VideoPlayerUdpateLinksReady` WHERE `Mp4_Link` != ''));

像這樣的東西(唯一的區別是我使用 2 個表):https://www.db-fiddle.com/f/91EW2kJDc8aWJYYvw86vG9/0

還嘗試了沒有任何運氣的變數:

SET @tblname := "wp_posts_duplicatedfortestonly";
SET @colname := "post_content";
SELECT @lookfor := SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) FROM @tblname WHERE `post_content` LIKE '%[flv:%';
SELECT @replacewith := `Png_Link` FROM `VideoPlayerUdpateLinksReady` WHERE `Mp4_Link` != '';

SET @qry = CONCAT('UPDATE ',@tblname, ' SET ', @colname, ' = REPLACE(' ,@colname, ',', @lookfor, ',',@replacewith,')');
PREPARE QUERY FROM @qry;
EXECUTE QUERY;

我在做什麼錯?是否可以將 SELECT 表達式用作 REPLACE 函式參數或我有什麼其他解決方法?

設法以我自己的菜鳥方式解決它:

1-由於我無法使 REPLACE 函式接受查詢作為參數,我只是將查詢結果插入到新表列中:

INSERT INTO VideoPlayerUdpate_FLV_links (`ID`,`PostTitle`,`AmazonLinks`) SELECT `ID`, `post_title`, SUBSTRING(`post_content`, LOCATE('[flv:',`post_content`), LOCATE(']',`post_content`) - LOCATE('[flv:',`post_content`) + 1) AS amazonlinks FROM wp_posts WHERE `post_content` LIKE '%[flv:%'

請記住,我有另一個表VideoPlayerUdpateLinksReady,其中包含我想要替換的所有新字元串。我必須手動建構並驗證此列VideoPlayerUdpateLinksReady.Png_Link中的所有錯誤,以便可以替換它。

2- 所以最後一步只是在 REPLACE 函式中使用這兩個表作為參數:

UPDATE `wp_posts_duplicatedfortestonly`  JOIN `VideoPlayerUdpate_FLV_links` ON wp_posts_duplicatedfortestonly.ID = VideoPlayerUdpate_FLV_links.ID  JOIN `VideoPlayerUdpateLinksReady` ON wp_posts_duplicatedfortestonly.ID = VideoPlayerUdpateLinksReady.ID SET `post_content` = REPLACE(`post_content`,VideoPlayerUdpate_FLV_links.AmazonLinks, VideoPlayerUdpateLinksReady.Png_Link)

而且我的所有內容都被替換了,沒有任何進一步的問題。

引用自:https://dba.stackexchange.com/questions/244147