但是这样并不能得到说有重复字段的id值。(只得到了最小的一个id值)查询哪些字段是重复的也容易:
SELECT `name`,count(`name`) as count FROM `table` GROUP BY `name` HAVING count(`name`) >1 ORDER BY count DESC;
但是要一次查询到重复字段的id值,就必须使用子查询了,于是使用下面的语句。
SELECT `id`,`name` FROM `table` WHERE `name` in (
SELECT `name`
FROM `table`
GROUP BY `name` HAVING count(`name`) >1);
但是这条语句在mysql中效率太差,感觉mysql并没有为子查询生成零时表。于是使用先建立零时表:
create table `tmptable` as (
SELECT `name`
FROM `table`
GROUP BY `name` HAVING count(`name`) >1);
然后使用多表连接查询:
SELECT a.`id`, a.`name` FROM `table` a, `tmptable` t WHERE a.`name` = t.`name`;
查询及删除重复记录的方法
delete from sp_member where id in (SELECT a.`id` FROM `sp_member` a, `tmptable` t WHERE a.`user_email` = t.`user_email`);
改为下面这条即可:
delete from sp_member where id in ( select c.id from (SELECT a.`id` FROM `sp_member` a, `tmptable` t WHERE a.`user_email` = t.`user_email`) c);