1. Introduction to Grammar
There are three tables A, B, C, and now you need to insert the values from table B and table C for each of several fields into the corresponding fields in table A. For this scenario, you can use the following statement to implement:
INSERT into Db1_name (field1,field2) SELECT field1,field2 from Db2_name
The above statement is more suitable for data interpolation for two tables if multiple tables are not adapted. For multiple tables, you can join the fields that need to be queried, then compose a view and select from:
INSERT into a (field1,field2) SELECT * FROM (SELECT b.f1,c.f2 from B JOIN c) as TB
Where F1 is the field of table B, F2 is the field of Table C, the fields from table B and table C are combined by a join query, and then inserted into table A by a select nested query, which satisfies this scenario where multiple joins can be used to combine fields if more than 2 tables are required.
2. Syntax error Note
It is important to note that the nested query section must finally have a set table alias, as follows:
SELECT * FROM (select f1,f2 from B JOIN c) as TB
That is, the last as TB is required (the name of TB can be arbitrarily taken), that is, to specify an alias. Each new derived table must specify an alias, otherwise the following error will be reported in MySQL:
ERROR 1248 (42000): Every derived TABLE must has its own alias
In addition, the insert into SELECT in MySQL cannot be addedto the values, i.e. it cannot be written as follows:
INSERT into Db1_name (field1,field2) VALUES SELECT field1,field2 from Db2_name