MySQL 中删除按除 ID 之外的所有分组的重复行的最佳方法?
似乎不是重复的,因为这个问题是不同的。
我的表有 3 列:id、col2、col3。我正在使用这种方法来删除重复的行:
create table temp_table as
select * from my_table where 1 group by col2,col3;
drop table my_table;
rename table temp_table to my_table;
然而,my_table 实际上有很多列,而不仅仅是 3 列,在查询中列出来很痛苦。所以我想问是否有一种方法可以进行这样的查询:
create table temp_table as
select * from my_table where 1 group by * except id;
drop table my_table;
rename table temp_table to my_table;
有可能的方法吗?
Doesn't seem to be a duplicate coz this question is different.
My table has 3 columns: id,col2,col3. I'm using this method to remove duplicated rows:
create table temp_table as
select * from my_table where 1 group by col2,col3;
drop table my_table;
rename table temp_table to my_table;
However, my_table actually has a lot of columns, not just 3, painfully to list out in the query. So I want to ask whether there's a way that we can do a query something like this:
create table temp_table as
select * from my_table where 1 group by * except id;
drop table my_table;
rename table temp_table to my_table;
Is there a possible way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行子查询以确保您获得的内容是唯一的。此查询将为您提供重复项(保留具有较低 ID 的重复项):
将它们放入临时表中(或将它们加载到 PHP)并运行第二个查询来删除。 (在读取数据时无法修改表)
执行
WHERE NOT EXISTS
来获取要保留的元素的 ID(同样,保留具有最低 ID 的元素)。You could do a sub-query to make sure that what you get is unique. This query will give you the duplicates (preserving the ones with the lower IDs):
throw them into a temporary table (or load them to PHP) and run a second query to
DELETE
. (You can't modify a table while you're reading from it)Do a
WHERE NOT EXISTS
to get the IDs of the elements to preserve (again, the ones with the lowest IDs are kept).我找到了一种方法“删除除 ID 之外的所有数据分组的重复行”,但它不纯粹是 MySQL,需要额外的 PHP 代码,而且太长了:
I found a method to "remove duplicated rows grouped by all except ID" but it's not purely MySQL, requires additional PHP code and damn long: