简体   繁体   中英

How to delete rows in MySQL which have same value for a column

I have something like this:

col1 col2 col3
A      B   C
A      B   C

I want only one row to remain out of these and other to be deleted. What query to implement?

If you want both duplicates to be removed, try this:

DELETE m.*
FROM mytable m
INNER JOIN
  (SELECT col1,
    col2,
    col3,
    COUNT(*)
  FROM mytable
  GROUP BY col1,
    col2,
    col3
  HAVING COUNT(*)>1
  ) t
ON m.col1 =t.col1
AND m.col2=t.col2
AND m.col3=t.col3

SQL Fiddle

EDIT

As you have edited your question and want one out of two duplicate rows to remain, you can easily achieve this with the following line:

  ALTER IGNORE TABLE mytable ADD UNIQUE INDEX idx_yourindexname (col1, col2, col3);

This will remove all of your duplicate rows, so that only unique ones are kept. The IGNORE keyword in compulsory because you already have data disobeying the INDEX in your table. Movereover, this will not allow for the duplicate insertions in the future.

You can try;

delete from table where col1 = 'A' and col2 = 'B' and col3 = 'C' limit 1;

You could use a record count, etc. in the limit clause to delete more records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM