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 祝福语驱散霉运的话简短