Mysql – thesql combine tables

MySQL

I have three tables which has the same schema. all of them has 10000000+ rows and has unique data as well as duplicate keys but with a datetime column can differentiate them and get the newest row.

I want to create a one combine table with all the data in my three tables updated with the newest records for duplicate values.

Suggest me a method to achieve this.

Best Answer

The UNION command should be your friend: http://dev.mysql.com/doc/refman/5.1/en/union.html

With UNION you can combine several SELECT results into one result. All selects must have the same field structure. In the MySQL docu there is a good example for your problem:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

You create a select for each of your tables with all filter and sorting you need and combine them with UNION to one select. The result of it can be stored by INSERT INTO ... SELECT ... in an archive table. You can also store this query in a MySQL view to have live data of all three tables with one select - Depending on the execution time / indexes etc.