useful mysql queries snippets

– remove duplicate records:
CREATE TEMPORARY TABLE temp_table (column1 VARCHAR(256),column2 VARCHAR(256));
INSERT INTO temp_table (`column1`,`column2`) SELECT DISTINCT `column1`,`column2` FROM table1;
DELETE from table1;
INSERT INTO table1 (`column1`,`column2`) SELECT * FROM temp_table;

– show duplicate records:
SELECT column1, count(*) FROM table1 GROUP BY id HAVING count(*) > 1;
or
select * from table1 i where i.id in
(SELECT id FROM table1 GROUP BY id HAVING count(*) > 1);

– set foreign key:
update table1 a, table2 b set a.fID=b.id where y.column1=i.column1;

– remove column:
alter table table1 drop column1;

– compare two columns to find unmatched records:
select column2 from table1
where column2 not in (select column1 from table1);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s