简体   繁体   English

使用PHP / MySQL从表中替换多个字符串

[英]Using PHP/MySQL to replace multiple strings from a table

I have a table called Products that contains Titles of products. 我有一个名为Products的表,其中包含产品标题。 Some of these Titles have words I would like to replace. 其中一些标题中有我想替换的词。 The table contains over 6,000 records. 该表包含6,000多个记录。 The text strings are found in the Title Column 文本字符串可在“ Title列中找到

ID | Title | Description | Price

I have another table called ReplaceText that contains a list of strings I am searching for and new text string. 我还有另一个名为ReplaceText表,其中包含要搜索的字符串列表和新的文本字符串。 (eg small | tiny) This currently has 102 records. (例如,小|小),目前有102条记录。

ID | OldString | NewString

I would like to create a PHP/MySQL script to search the Title field in the Products table for matching words from the 'OldString field in the ReplaceText` table. 我想创建一个PHP / MySQL脚本来搜索Products表中的Title字段,以匹配ReplaceText表中OldString field in the单词。

I have tried various methods but all can't crack the code. 我尝试了各种方法,但都无法破解代码。 Please help :) 请帮忙 :)

Thank you in advance. 先感谢您。

I suggest the following approach, using only SQL queries. 我建议仅使用SQL查询的以下方法。

First, create a temporary table ProductsTMP containing only the rows Products with a new Title . 首先,创建一个临时表ProductsTMP ,该表仅包含具有新Title Products行。

CREATE TEMPORARY TABLE ProductsTMP AS
SELECT p.ID, r.NewString AS Title, p.Description, p.Price
FROM Products p INNER JOIN ReplaceText r ON p.Title = r.OldString;

Then, remove the old rows from the original Products table: 然后,从原始“ Products表中删除旧行:

DELETE FROM Products
WHERE ID IN (SELECT ID FROM ProductsTMP);

Finally, add the updated rows from ProductsTMP to the original table Products , and remove the temporary table: 最后,将ProductsTMP更新的行添加到原始表Products ,并删除临时表:

INSERT INTO Products (ID, Title, Description, Price)
SELECT ID, Title, Description, Price FROM ProductsTMP;    
DROP TABLE ProductsTMP;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM