题
这显示了我所有的名字,并且具有完全相同的两个条目是姓氏相同
SELECT `firstname`,`lastname`,COUNT(*) AS Count
FROM `people`
GROUP BY `firstname`,`lastname`
HAVING Count = 2
我如何变成一个删除这个WHERE用了限制语句只删除每个条目中的一个,并留下另一个。
没关系,这似乎是办法的技术我只是打算做一个PHP while循环
解决方案
您可以创建一个表,每个副本的的1条。然后删除从百姓餐桌的所有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;
其他提示
如果你有一个主键,诸如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
,以避免子查询。
创建一个新的表,并添加(名字,姓氏)的唯一密钥。然后将旧表中的行插入到新表。然后重命名表。
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)
不隶属于 StackOverflow