MYSQL删除重复记录SQL

表letter_detail

字段id,book_chapter_id,word

其中2个字段book_chapter_id,word有重复的需要删除掉,只保留一条

查询重复的:

SELECT MIN(id),COUNT(1) aa  
FROM letter_detail
GROUP BY letter_detail.book_chapter_id,letter_detail.word
HAVING aa>1


写了个SQL删除 结果报错,不能在更新的时候同时检索这个表

Error Code : 1093
You can't specify target table 'letter_detail' for update in FROM clause


DELETE FROM letter_detail WHERE (letter_detail.book_id,letter_detail.book_chapter_id,letter_detail.word )
IN(SELECT ld.book_id,ld.book_chapter_id,ld.word
FROM letter_detail ld
GROUP BY ld.book_id,ld.book_chapter_id,ld.word
HAVING COUNT(1)>1)
AND letter_detail.id NOT IN(SELECT MIN(id)
FROM letter_detail ld
GROUP BY ld.book_id,ld.book_chapter_id,ld.word
HAVING COUNT(1)>1)


重新改下:

查询SQL:

SELECT t1.id,t1.word  FROM letter_detail t1
,  (SELECT ld.book_chapter_id,ld.word,MIN(id) id
	FROM letter_detail ld
	GROUP BY ld.book_id,ld.book_chapter_id,ld.word
	HAVING COUNT(1)>1 
) AS minld
WHERE t1.book_id=3 AND t1.word=minld.word AND t1.id !=minld.id

删除SQL(将上面的查询作为子表):

DELETE ma FROM letter_detail ma, 
(
SELECT t1.id,t1.word  FROM letter_detail t1
,  (SELECT ld.book_chapter_id,ld.word,MIN(id) id
	FROM letter_detail ld
	GROUP BY ld.book_id,ld.book_chapter_id,ld.word
	HAVING COUNT(1)>1 
) AS minld
WHERE t1.book_id=3 AND t1.word=minld.word AND t1.id !=minld.id ) mb WHERE ma.book_id=3 AND ma.id=mb.id

我的多写了个book_id=3的限定条件。至此搞定。

不会再报该死的You can't specify target table '*****l' for update in FROM clause了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值