MYSQL deletes duplicate records and retains only the maximum ID

Source: Internet
Author: User

Table:productprice

Table Column:id, Productasin ...

The same productasin only retains the most recent one, that is, only the maximum ID is reserved.

First step: Detect duplicate records and maximum IDs

SELECT Productasin,max (ID) maxid
From Productprice GROUP by Productasin have COUNT (ID) >= 2)
Tempt

Step two: Isolate the record in duplicate and less than the maximum ID

SELECT productprice.id as ID from
Productprice Productprice, (SELECT Productasin,max (ID) maxid
From Productprice GROUP by Productasin have COUNT (ID) >= 2)
Tempt
WHERE Productprice.productasin = Tempt.productasin
and Productprice.id < Tempt.maxid

Step Three: Delete

DELETE from Productprice WHERE ID in (
SELECT Tempout.id from
(
SELECT productprice.id as ID from
Productprice Productprice, (SELECT Productasin,max (ID) maxid
From Productprice GROUP by Productasin have COUNT (ID) >= 2)
Tempt
WHERE Productprice.productasin = Tempt.productasin
and Productprice.id < TEMPT.MAXID) Tempout)
;

The temp table tempout is to prevent MySQL ERROR:

MYSQL Error:error code:1093. You can ' t specify target table ' Productprice ' for update in FROM clause

Example:productprice table The same day, the same productasin only the one with the largest ID

DELETE from Productprice WHERE ID in (
SELECT Tempout.id from
(
SELECT productprice.id as ID from
Productprice Productprice, (SELECT productasin,date_format (createddate, '%y-%m-%d ') as Tempdate,max (ID) maxId
From Productprice GROUP by Date_format (CreatedDate, '%y-%m-%d '), Productasin have COUNT (ID) >= 2)
Tempt
WHERE Productprice.productasin = Tempt.productasin and Date_format (productprice.createddate, '%Y-%m-%d ') = Tempt.tempdate
and Productprice.id < TEMPT.MAXID) tempout)
;

MYSQL deletes duplicate records and retains only the maximum ID

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.