Five usages of insert statement in mysql


foreword

The insert statement is the syntax in standard sql, which means inserting data. In practical applications, it has also evolved many usages to achieve special functions. The following introduces five usages of the insert statement in the mysql database.

1. Insert a single line after the values ​​parameter

grammar:

insert into tableName (colunm1,colunm2,...) value(value1,value2,...);

If you insert multiple pieces of data, you need to write multiple pieces of sql.

insert into a(id,name,type) values (1,'A1','T1');
insert into a(id,name,type) values (2,'A2','T2');

2. Insert multiple lines after the values ​​​​parameter

grammar:

insert into tableName(colunm1,colunm2,..) values(value1,value2...),(value1,value2...);

One sql for multiple pieces of data is enough, which is more efficient than method 1.

insert into a(id,name,type) values (1,'A1','T1'),(2,'A2','T2');

3. Insert data with select

grammar:

insert into tableName(colunm1,colunm2,..) select colunm1,colunm2,..;

Multiple pieces of data can be associated using union all.

insert into a(id,name,type)
	select 1,'A1','T1'
	union all
	select 2,'A2','T2';

4. Copy the information from the old table to the new table

grammar:

insert into tableName(colunm1,colunm2,..) select colunm1,colunm2,.. from tableName1;

Assuming that the table structure of the two tables is the same, the statement is as follows, otherwise, please specify the field name.

insert into a select * from b where id=1;

5. Insert data with set

grammar:

insert into tableName  set colunm1=value1,colunm2=value2....;

Using set is an extended writing method, which can accurately assign values ​​to columns and prevent data errors caused by disordered order during assignment. At the same time, this writing method inserts data faster, but it is not suitable for batch loop insertion.

insert into a set id=1,name='A1',type='T1';

Summarize

Word document download address: Five usages of insert statement in mysql

Guess you like

Origin blog.csdn.net/ma286388309/article/details/129276060