PHP+MYSQL 两行Query搞定删除重复数据

$db=mysql_connect('localhost','xxx','xxx');
//text为可能存在重复的字段名,先用count子句来把TEXT重复的记录的ID拎出来,不全拎,节省资源~

mysql_select_db('vbnew');
$sql="SELECT id, text, count( text )
FROM `dic`
GROUP BY text
HAVING count( text ) >1";
$result=mysql_query($sql)or die("Invalid query: " . mysql_error());
$i=1;
//把S出来的记录的ID做成Array

while($ids=mysql_fetch_array($result))
{
$id[$i]=$ids[0];
echo $ids[0];
echo "id为".$id[$i];
echo "
";
$i++;
}
//开始爽删~

foreach($id as $a=>$b)
{
$sql="delete from dic where id=".$b."";
mysql_query($sql);
echo "成功删除1行,id为".$b;
echo "
";
}
?>

//做个小结 也算是个疑问吧 就是本来想着这种方法应该是把所有重复的记录都删掉,没想到却恰好留一条,也算歪打正着吧~

4 thoughts on “PHP+MYSQL 两行Query搞定删除重复数据

    1. coder4

      06年前写的了,方法虽然很幼稚,但还确实是我写的,后来换了几次博客,所以在这里的日期是09年。原文地址http://liheyuan.bokee.com/5373517.html。你在百度上搜到其他结果无非是直接转载我写的没注明出处罢了,我转载的文章都会注明出处的。

      Reply

Leave a Reply to yyy Cancel reply

Your email address will not be published. Required fields are marked *