mysql delete duplicate records and keep one

-- method one
/**

Error code: 1093
You can't specify target table 'an' for update in FROM clause
Tables used in select cannot be modified at the same time
**/
DELETE an  FROM  t_anchor_cp an

WHERE an.c_order IN
(

	SELECT t0.c_order FROM t_anchor_cp t0,(

	SELECT t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no FROM t_anchor_cp t1 GROUP BY
	t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no HAVING COUNT(*)>1

	)t2

	WHERE t0.c_anchor_no = t2.c_anchor_no
	AND t0.c_foreign_id = t2.c_foreign_id
	AND t0.c_line_type_id = t2.c_line_type_id
	AND t0.c_order NOT IN
	(
	SELECT MIN(c_order) FROM t_anchor_cp t1 GROUP BY
	t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no HAVING COUNT(*)>1

	)

)


-- Method 2 successfully executed using temporary table
DELETE an  FROM  t_anchor_cp an,(

	SELECT t0.c_order FROM t_anchor t0,(

	SELECT t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no FROM t_anchor_cp t1 GROUP BY
	t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no HAVING COUNT(*)>1

	)t2

	WHERE t0.c_anchor_no = t2.c_anchor_no
	AND t0.c_foreign_id = t2.c_foreign_id
	AND t0.c_line_type_id = t2.c_line_type_id
	AND t0.c_order NOT IN
	(
	SELECT MIN(c_order) FROM t_anchor_cp t1 GROUP BY
	t1.c_foreign_id,t1.c_line_type_id,t1.c_anchor_no HAVING COUNT(*)>1

	)

)tt
WHERE tt.c_order = an.c_order


-- Method 3 Create a temporary table for query, if the amount of data is small
CREATE TABLE t_anchor_cp SELECT * FROM t_anchor




MySQL Error 1093 - Can't specify target table for update in FROM clause

quote

***************
*Cheekysoft:***
***************
In MySQL, you can't modify the same table which you use in the SELECT part.
Alternatively, try nesting the subquery deeper into a from clause ...

If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance:

UPDATE tbl SET col = (
  SELECT ... FROM (SELECT.... FROM) AS x);

The nested subquery in the FROM clause creates an implicit temporary table, so it doesn't count as the same table you're updating.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326118085&siteId=291194637