当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql一些复杂的sql语句(查询与删除重复的行)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

花乡世界名园,儿童套房,满天飘着六月的雪

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;

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网