这显示了所有具有两个完全相同的条目的名字和姓氏
SELECT `firstname`,`lastname`,COUNT(*) AS Count
FROM `people`
GROUP BY `firstname`,`lastname`
HAVING Count = 2
如何将其转换为带有LIMIT的DELETE FROM WHERE语句,只删除其中一个条目并保留另一个条目。
好吧这似乎是技术的方式我只是在php while while循环
答案 0 :(得分:2)
您可以创建一个包含每个重复项的1条记录的表:然后从人员表中删除所有重复记录,然后重新插入重复记录。
-- 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;
答案 1 :(得分: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
避免子查询。
答案 2 :(得分: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)