mysql关于[重复记录]查询
distinct可以列出不重复的记录:
-
SELECT DISTINCT `title` FROM `table`
注意:
但是distinct查出结果只有一个字段的数据,要想同时还用到别的数据就不能用它了。
完美解决distinct中使用多个字段的方法:
众所周知,distinct可以列出不重复的记录,对于单个字段来说distinct使用比较简单,但是对于多个字段来说,distinct使用起来会使人发狂。而且貌似也没有见到微软对distinct使用多字段的任何说明。下面就提供了一种方法可以在使用distinct的时候同时使用多个字段。
select 要使用字段1,要使用字段2或者(*) from 表名 where `id` in (select min(`id`) from 表名 group by 不重复字段名)
例:
1
|
select
id,title
from
bbs
where
id
in
(
select
min
(id)
from
bbs
group
by
title)
|
==========================================================================
列出重复记录并列出来:
单表单个字段重复:
-
SELECT * FROM `table` WHERE `title` IN (SELECT `title` FROM `table` GROUPBY `title` HAVINGCOUNT(`title`) > 1)
单表两字段重复:
-
SELECT * FROM `table` a WHERE (a.aid,a.username) IN (SELECT aid,username FROM `table` GROUPBY aid,username HAVINGCOUNT(*) > 1)
php删除重复记录只保留一条:
-
$db=mysql_connect('localhost','xxx','xxx');
-
mysql_select_db('vbnew');
-
$i=1;
-
$sql="SELECT id, text, count( text ) FROM `dic` GROUP BY text HAVING count( text ) >1";
-
$result=mysql_query($sql);
-
while($ids=mysql_fetch_array($result)){
-
$id[$i]=$ids[0];
-
echo$ids[0];
-
echo"id为".$id[$i];
-
echo"<br>";
-
$i++;
-
}
-
foreach($idas$a=>$b){ //开始删除
-
$sql="delete from dic where id=".$b."";
-
mysql_query($sql);
-
echo"成功删除1行,id为".$b;
-
echo"<br>";
-
}