欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mysql一些复杂的sql语句(查询与删除重复的行)

程序员文章站 2022-07-05 11:17:29
1.查找重复的行 select * from blog_user_relation a where (a.account_instance_id,a.follow...

1.查找重复的行

select * from blog_user_relation a where (a.account_instance_id,a.follow_account_instance_id) 
in (select account_instance_id,follow_account_instance_id from blog_user_relation group by account_instance_id, follow_account_instance_id having
 count(*) > 1)

2.删除重复的行(保留一条)

ps:因为mysql的delete,如果被删的表的where条件里有in,且in里面也有此表,那就删除不了。

/*创建个临时表*/
create table blog_user_relation_temp as
(
 select * from blog_user_relation a where 
 (a.account_instance_id,a.follow_account_instance_id) 
 in ( select account_instance_id,follow_account_instance_id from blog_user_relation group by account_instance_id, follow_account_instance_id having count(*) > 1)
 and 
 relation_id 
 not in (select min(relation_id) from blog_user_relation group by account_instance_id, follow_account_instance_id having count(*)>1));

/*删除数据*/
delete from `blog_user_relation` where relation_id in (select relation_id from blog_user_relation_temp);

/*删除临时表*/
drop table blog_user_relation_temp;