-
Create a new table
CREATE TABLE records_new LIKE records; -
Add composite
UNIQUEconstraint preventing duplicates in the futureALTER TABLE records_new ADD UNIQUE idx_composite_UNIQUE (site_id ASC, session_id ASC, query ASC, remote_addr ASC); -
Copy records over.
INSERT INTO records_new SELECT * FROM records ORDER BY id ON DUPLICATE KEY UPDATE records_new.created=NOW();The above updates
createdtoNOW()on every duplicate hit, but if you don't want that, change it toON DUPLICATE KEY UPDATE records_new.id=records_new.id(whereidis the table'sPRIMARY KEY), which does nothing -
Swap the table names
RENAME TABLE records TO records_old, records_new TO records;
This has been to a large extent based on César Revert-Gomar's answer, so credits to the author.