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;
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短