1. Introduction to Grammar
There are three tables A, B, and C, and now you need to insert the values from table B and table C to find the corresponding fields in table A. For this situation, 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 in two tables, if multiple tables are not adapted. For multiple tables, you can join the fields you want to query, then make 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, a join query combines fields from table B and Table C, and then inserts a select nested query into Table A, which satisfies the scenario, and if more than 2 tables are required, you can combine the fields in the form of multiple joins.
2. Grammatical error attention
It is important to note that the nested query section must finally have a table alias set, as follows:
SELECT * FROM (select f1,f2 from B JOIN c) as TB
That the last as TB is required (TB is a name that can be arbitrarily taken), that is, specify an alias. Each derived new table must have an alias specified, otherwise the following error will be reported in MySQL:
ERROR 1248 (42000): Every derived TABLE must have its own alias
In addition, insert into select in MySQL cannot add values, that is, cannot be written in the following form:
INSERT into Db1_name (field1,field2) VALUES SELECT field1,field2 from Db2_name
Otherwise there will be an error: "Have an error in your SQL syntax