mysql关于[重复记录]查询


distinct可以列出不重复的记录:

  1. 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 不重复字段名)


例:

select id,title from bbs where id in (select min(id) from bbs group by title)


==========================================================================


列出重复记录并列出来:

单表单个字段重复:

  1. SELECT * FROM `table` WHERE `title` IN (SELECT `title` FROM `table` GROUPBY `title` HAVINGCOUNT(`title`) > 1)


单表两字段重复:

  1. SELECT * FROM `table` a WHERE (a.aid,a.username) IN (SELECT aid,username FROM `table` GROUPBY aid,username HAVINGCOUNT(*) > 1)


php删除重复记录只保留一条:


  1. $db=mysql_connect('localhost','xxx','xxx');  

  2. mysql_select_db('vbnew');  

  3. $i=1;  

  4. $sql="SELECT id, text, count( text ) FROM `dic` GROUP BY text HAVING count( text ) >1";

  5. $result=mysql_query($sql);

  6. while($ids=mysql_fetch_array($result)){  

  7. $id[$i]=$ids[0];  

  8. echo$ids[0];  

  9. echo"id为".$id[$i];  

  10. echo"<br>";  

  11. $i++;  

  12. }

  13. foreach($idas$a=>$b){                     //开始删除

  14. $sql="delete from dic where id=".$b."";  

  15.    mysql_query($sql);  

  16. echo"成功删除1行,id为".$b;  

  17. echo"<br>";  

  18. }

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!