这将显示具有两个完全相同的条目的所有名字和姓氏
SELECT `firstname`,`lastname`,COUNT(*) AS Count
FROM `people`
GROUP BY `firstname`,`lastname`
HAVING Count = 2如何将其转换为DELETE FROM WHERE语句,限制为只删除每个条目中的一个,保留另一个条目。
好的,这似乎是一种技术上的方法,我将在php while循环中实现它。
发布于 2010-01-27 21:05:38
您可以为每个重复项创建一个包含1条记录的表:然后从people表中删除所有dup记录,然后重新插入这些dup记录。
-- Setup for example
create table people (fname varchar(10), lname varchar(10));
insert into people values ('Bob', 'Newhart');
insert into people values ('Bob', 'Newhart');
insert into people values ('Bill', 'Cosby');
insert into people values ('Jim', 'Gaffigan');
insert into people values ('Jim', 'Gaffigan');
insert into people values ('Adam', 'Sandler');
-- Show table with duplicates
select * from people;
-- Create table with one version of each duplicate record
create table dups as
select distinct fname, lname, count(*)
from people group by fname, lname
having count(*) > 1;
-- Delete all matching duplicate records
delete people from people inner join dups
on people.fname = dups.fname AND
people.lname = dups.lname;
-- Insert single record of each dup back into table
insert into people select fname, lname from dups;
-- Show Fixed table
select * from people;发布于 2010-01-27 21:05:19
如果你有一个主键,比如id,你可以这样做:
delete from people
where id not in
(
select minid from
(select min(id) as minid from people
group by firstname, lastname) as newtable
)子查询select min(id)...位为您获取给定名字、姓氏组合的唯一行(基于id);然后删除所有其他行,即您的重复行。由于mysql中的错误,您需要包装您的子查询,否则我们可以这样做:
delete from people
where id not in
(
select min(id) as minid from people
group by firstname, lastname
)更好的方法是:
delete people from
people left outer join
(
select min(id) as minid from people
group by firstname, lastname
) people_grouped
on people.first_name = people_grouped.first_name
and people.last_name = people_grouped.last_name
and people_grouped.id is null以避免子查询。
发布于 2010-01-27 21:24:42
创建一个新表,并在(名字,姓氏)上添加一个唯一的键。然后将旧表中的行插入到新表中。然后重命名这些表。
mysql> select * from t;
+-----------+----------+
| firstname | lastname |
+-----------+----------+
| A | B |
| A | B |
| X | Y |
+-----------+----------+
3 rows in set (0.00 sec)
mysql> create table t2 like t;
Query OK, 0 rows affected (0.00 sec)
mysql> alter table t2 add unique key name(firstname,lastname);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> insert ignore into t2 select * from t;
Query OK, 2 rows affected (0.00 sec)
Records: 3 Duplicates: 1 Warnings: 0
mysql> select * from t2;
+-----------+----------+
| firstname | lastname |
+-----------+----------+
| A | B |
| X | Y |
+-----------+----------+
2 rows in set (0.01 sec)https://stackoverflow.com/questions/2146938
复制相似问题