查找并替换数据库中的重复字符串

时间:2012-07-31 11:30:01

标签: php mysql string

我在我的talbe的某些行中有问题的数据,如跟随字符串

[data attr1='2300.48' attr1='1' attr1='1116.95' attr1='60.75' attr1='9.22' attr1='' attr1='0' attr1='3593.39' attr1='119.05' attr1='25.96' attr1='27.98' attr1='36.32']

[data attr1='2300.48' attr1='1' attr1='1116.95' attr1='60.75' attr1='9.22' attr1='' attr1='0' attr1='3593.39' attr1='119.05' attr1='25.96' attr1='27.98' attr1='36.32']

[data attr1='2300.48' attr1='1' attr1='1116.95' attr1='60.75' attr1='9.22' attr1='' attr1='0' attr1='3593.39' attr1='119.05' attr1='25.96' attr1='27.98' attr1='36.32']

[data attr1='2300.48' attr1='1' attr1='1116.95' attr1='60.75' attr1='9.22' attr1='' attr1='0' attr1='3593.39' attr1='119.05' attr1='25.96' attr1='27.98' attr1='36.32'] 

现在我想用一个相同的字符串替换它们,如:

[data attr1='2300.48' attr1='1' attr1='1116.95' attr1='60.75' attr1='9.22' attr1='' attr1='0' attr1='3593.39' attr1='119.05' attr1='25.96' attr1='27.98' attr1='36.32']

请注意,attr的值会有所不同。

- 更新 -

如何将其存储在数据库中 列名称为content,此列中的值为

the text of the article
 [data.... ]
 [data.... ]
 [data.... ]

content的数据类型为longtext

抱歉,我无法建立正确的sql表结构。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您可以使用DISTINCTGROUP BY删除重复值,具体取决于其他需求。例如:

select distinct mycolumn from mytable;

或者:

select mycolumn from mytable group by mycolumn;

答案 1 :(得分:0)

如果要删除/删除重复的行,可以使用

DELETE t 
FROM t 
LEFT JOIN t AS t2 ON (t.content = t2.content AND t.id > t2.id) 
WHERE t2.id;

在:

SELECT * FROM t;
+----+---------+
| id | content |
+----+---------+
|  1 | abc     |
|  5 | abc123  |
|  9 | abc123  |
| 13 | abc     |
| 17 | abc     |
+----+---------+

后:

SELECT * FROM t;
+----+---------+
| id | content |
+----+---------+
|  1 | abc     |
|  5 | abc123  |
+----+---------+

答案 2 :(得分:0)

这是让我工作的脚本。

$link = mysqli_connect("SERVER", "root", "root");
    $db = mysqli_select_db($link, "test");
    $res = mysqli_query($link, "SELECT * FROM wp_posts WHERE post_content LIKE '%nutr-label servingsize%nutr-label servingsize%'");

    if($res){
        $i=1;
        while($row = mysqli_fetch_array($res)){
            $str1 = strrpos($row['post_content'],"[nutr-label servingsize='");
            $sub1 = substr($row['post_content'],$str1);
            $str2 = strrpos($row['post_content'],"']");

            $finalStr = substr($row['post_content'],$str1,$str2);
            $newPostContent = substr($row['post_content'], 0, strpos($row['post_content'],"[nutr-label servingsize='")).$finalStr;
            $up = mysqli_query($link,"UPDATE wp_posts SET post_content ='".addslashes($newPostContent)."' WHERE ID='".$row['ID']."'");
            $i++;
        }
    }else{
        echo mysqli_error();
    }