You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用MySQL删除所有重复条目(不保留任一行)

Delete All Duplicate Rows (No Entries Kept from Duplicate Groups) in MySQL

Got it, let's sort this out for you. You need to remove every row that’s part of a duplicate group—meaning if an RFID value appears more than once, all rows with that RFID get deleted, leaving only rows with completely unique RFID values. Your current SQL statement won’t work because MySQL doesn’t support that syntax for DELETE, and the common "keep max/min ID" trick isn’t what you’re after here.

Why Your Current Query Fails

The statement DELETE * ,count(*)as n FROM cart by rfid HAVING n>1 is invalid because:

  • You can’t include aggregate functions like COUNT(*) directly in a DELETE clause
  • The GROUP BY syntax here isn’t compatible with MySQL’s DELETE operation rules

Solution 1: Subquery to Target Duplicate RFIDs

This method first identifies all RFID values that have duplicates, then deletes every row linked to those RFIDs:

DELETE FROM cart
WHERE RFID IN (
    SELECT RFID
    FROM cart
    GROUP BY RFID
    HAVING COUNT(*) > 1
);

Solution 2: JOIN (Better for Large Tables)

If your table has a lot of data, a JOIN-based approach often performs better than an IN subquery. It achieves the exact same result:

DELETE c
FROM cart c
JOIN (
    SELECT RFID
    FROM cart
    GROUP BY RFID
    HAVING COUNT(*) > 1
) dup ON c.RFID = dup.RFID;

Always Verify Before Deleting!

Never run a DELETE blind—preview which rows will be removed first by swapping DELETE with SELECT *:

SELECT * FROM cart
WHERE RFID IN (
    SELECT RFID
    FROM cart
    GROUP BY RFID
    HAVING COUNT(*) > 1
);

For your sample data, this will return the two rows with RFID=1—exactly the ones you want to erase. After running the DELETE, only rows with RFID=2 and RFID=3 will stay.

Quick Tips

  • Backup first: Always create a backup or run the DELETE in an InnoDB transaction so you can roll back if something goes wrong.
  • Adjust for multi-column duplicates: If duplicates are defined by more than one column (e.g., RFID + CATAGORY), just add those columns to the GROUP BY clause in the subquery.

内容的提问来源于stack exchange,提问作者Akhila Bhaskar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:19:05