Ways to merge several tables into one so record IDs match chronological order (consolidation)

Lecture



If you want to merge several tables into one so that the values of the "ID" column in the merged table correspond to time-based values, it's assumed that the "ID" column contains timestamps or values you want to sort by.

Ways to merge several tables into one so record IDs match chronological order (consolidation)

Say you have several tables: table1, table2 and table3, and each of them has an "ID" column representing timestamps. You want to merge them into one table, merged_table, while preserving the time order.

  1. Create the merged_table table with the needed columns:
CREATE TABLE merged_table
   ( ID INT PRIMARY KEY,
    other_columns... -- list the remaining columns here
);
  1. Insert the data from all the tables into merged_table, preserving the time order:
INSERT INTO merged_table (other_columns...)
   SELECT other_columns... FROM table1
    UNION ALL
   SELECT other_columns... FROM table2
    UNION ALL
   SELECT other_columns... FROM table3
ORDER BY time_created;

In this query, UNION ALL is used to merge data from the different tables, and ORDER BY

time_created

ensures that the data is ordered by time.

Please make sure you've specified the column and table names correctly according to your data schema.

If one of the tables has IDs linked to other tables, while the others don't have such links, then to keep the changes minimal you can use negative IDs for the tables being merged

if you don't need to save the data, use queries like these but without INSERT

 SELECT other_columns... FROM table1
    UNION ALL
   SELECT other_columns... FROM table2
    UNION ALL
   SELECT other_columns... FROM table3 

or

SELECT * FROM `table1`

  LEFT JOIN `table2` AS PR ON table1.id=table2.relation_id

See also

  • UNION
  • JOIN
  • LEFT JOIN
  • RIGHT JOIN

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases - MySql (Maria DB)"

Terms: Databases - MySql (Maria DB)