Mysql一些复杂的sql语句(查询与删除重复的行)
1.查找重复的行
SELECT*FROMblog_user_relationaWHERE(a.account_instance_id,a.follow_account_instance_id) IN(SELECTaccount_instance_id,follow_account_instance_idFROMblog_user_relationGROUPBYaccount_instance_id,follow_account_instance_idHAVING COUNT(*)>1)
2.删除重复的行(保留一条)
PS:因为mysql的delete,如果被删的表的where条件里有in,且in里面也有此表,那就删除不了。
/*创建个临时表*/ CREATETABLEblog_user_relation_tempAS ( SELECT*FROMblog_user_relationaWHERE (a.account_instance_id,a.follow_account_instance_id) IN(SELECTaccount_instance_id,follow_account_instance_idFROMblog_user_relationGROUPBYaccount_instance_id,follow_account_instance_idHAVINGCOUNT(*)>1) AND relation_id NOTIN(SELECTMIN(relation_id)FROMblog_user_relationGROUPBYaccount_instance_id,follow_account_instance_idHAVINGCOUNT(*)>1)); /*删除数据*/ DELETEFROM`blog_user_relation`WHERErelation_idIN(SELECTrelation_idFROMblog_user_relation_temp); /*删除临时表*/ DROPTABLEblog_user_relation_temp;
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短