MySQL can insert data to a specified table based on the queried record set. the following example describes the structure of the three tables: s (sno, snamesex, age, dept) student information table c (cno, cname, tname) course information table SC (sno, cno, grade) MySQL can be inserted to a specified table based on the queried record set. The example is:
First, describe the structure of the three tables:
S (sno, sname. sex, age, dept) // student information table
C (cno, cname, tname) // course information table
SC (sno, cno, grade) // optional course information table
Now the problem is:
Insert the student ID, name, and system name of a course score greater than or equal to 80 into an existing (to be created) basic table stu (sno, sname, dept ).
The existing database Schema of the stu table is:
drop table if EXISTS stu ;create table stu ( sno int(4) unique , sname varchar(20), dept varchar(10));
Now write the SQL statement of the result:
insert into stu (sno,sname,dept)select sno ,sname , dept from s wheres.sno in (select sc.sno from sc where sc.grade >= 80 );
The following are the syntax rules of the preceding SQL statement:
Insert into table name 1 (field list 1) SELECT field list 2 FROM table name 2 WHERE condition expression;
Table name 1: indicates the table to which the record is inserted. Field list 1: indicates which fields are assigned values. Field list 2: The data of the fields queried from the table. Table name 2: indicates the table from which the record is queried. Conditional expression: specifies the query conditions for SELECT statements.
After the records queried in "table name 2" are inserted into "table name 1", the original records are still saved in "table name 2.
Tip:
When using this method, you must ensure that the number of fields in "field list 1" and "field list 2" is the same, make sure that the data type of each corresponding field is the same. If the data types are different, the database system reports an error. Then, the INSERT statement is blocked from being executed downward.