How do i join 3 or more tables in mysql as follows?
- there is a column for each column of each table (except ID)
- ID field values all go into the same ID field in the new table
- an additional column is added called
tablethe values of which is the source Table name - an autoincremented
newIDfield is added - only one table contributes to each row, unrelated fields have null values
- total number of rows is equal to the sum records from all tables
example with just two tables :
TableA: TableB
ID | fieldA ID | fieldB
----------------- -----------------
1 | valueA1 1 | valueB1
2 | valueA2 2 | valueB2
ResultTable:
newID | ID | table | fieldA | fieldB
---------------------------------------------
1 | 1 | TableA | valueA1 |
2 | 2 | TableA | valueA2 |
3 | 1 | TableB | | valueB1
4 | 2 | TableB | | valueB2
I know this probably sounds a bit weird!. I am going to try and use this to batch insert nodes for records from various tables into neojs graph database with this batch-insert script. which could be hilarious considering I hardly know what I am doing in either database 😉 .
Try this one,
SQLFiddle Demo
here’s the proposed schema
here’s the query using
INSERT INTO...SELECTstatement