Hi Here i came across a situation in which by mistakenly Without dropping the table i have run the batch file of the table which consists of some insert statements in detail
First , consider setting your ID
fields as AI (auto increasment) and even PK (Primary Key).
In order to remove those duplicated rows , we will create a new table and will move all those duplicated rows to it. After that , drop that table.
CREATE TEMPORARY TABLE bad_temp AS SELECT DISTINCT * FROM alert_priority
you can copy all unique records into a new table, then delete the old table:
SELECT DISTINCT * INTO new_table FROM old_table
CREATE TABLE new_tbl(id int AUTO_INCREMENT,priority_name);
INSERT INTO new_tbl
select priority_name from old_tbl group by priority_name;
To just delete the duplicate new rows and leave the old ones in place (on the basis that I assume there are already other tables whose rows refer to the original rows):-
DELETE FROM alert_priority
WHERE Id IN (SELECT MaxId
FROM (SELECT priority_name, MAX(Id) AS MaxId, COUNT(Id) AS CountId
FROM alert_priority
GROUP BY priority_name
HAVING CountId > 1))
Following query will give you all records that you want to keep:
SELECT min(id)
FROM alert_priority
GROUP BY priority_name
HAVING count(*) > 1
OR min(id) = max(id)
To remove all duplicates, run this query:
DELETE FROM alert_priority
WHERE id NOT IN (
SELECT min(id)
FROM alert_priority
GROUP BY priority_name
HAVING count(*) > 1
OR min(id) = max(id)
)
In SQL-Server it would be easy using ROW_NUMBER, but alas MySQL doesn't have a function like that :-(
Best way to solve it would be as follows:
INSERT INTO name_of_new_table SELECT DISTINCT * FROM name_of_old_table