4

这向我显示了所有有两个完全相同的条目的名字和姓氏

SELECT `firstname`,`lastname`,COUNT(*) AS Count 
FROM `people` 
GROUP BY `firstname`,`lastname`
HAVING Count = 2

如何将其转换为带有 LIMIT 的 DELETE FROM WHERE 语句,以仅删除每个条目中的一个并保留另一个条目。

好吧,这似乎是技术的方式我只是要在 php while 循环中做到这一点

4

3 回答 3

2

您可以创建一个包含每个重复项的 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-27T13:05:37.563 回答
1

如果你有一个主键,比如 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-27T13:05:18.657 回答
0

创建一个新表并在 (firstname,lastname) 上添加一个唯一键。然后将旧表中的行插入到新表中。然后重命名表。

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)
于 2010-01-27T13:24:42.183 回答