MySQL Hack: Storing Only the UNIQUE Records In a Table and deleting the rest!

Nishant Arora 27/Oct/2011
Facebook
Twitter
LinkedIn
Reddit

while working on my website http://pksongsdownload.org/, I had to add some sample searches to start the ball rolling, so I have a database having two columns, term and link

so the data is simply "Search Term" and "Corresponding Link" like "Rafta Rafta" and "http://pksongsdownload.org/search.php?search=Rafta%2cRafta&type=mp3&page=1"

So the issue is while adding data to the database, the data might get repeated so how to get rid of that, the hack is very simple:

CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY column_name;
DROP TABLE old_table;
RENAME TABLE new_table TO old_table;

execute after all data is added, so I will explain how this works

  1. CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by]; =>> this will create a new table based on the previous table, by selecting unique records based upon a particular column called column_name.
  2. DROP TABLE old_table; =>> this will kill the old table, so we are left with only the unique one.
  3. RENAME TABLE new_table TO old_table; =>> Simply rename the new table to old table, and you are done.
It is that simple, enjoy!
Cheers