MySQL must know must know the study notes Chapter 19 Insert Data

Insertion can be done in the following ways:
1. Insert a complete row.
2. Insert part of the row.
3. Insert multiple rows.
4. Insert the results of some queries.

For each table or each user, use MySQL's security mechanism to prohibit the use of INSERT statements.

There is no output from the insert statement.

Insert a complete line:

INSERT INTO tableName
VALUES(fieldsValueList);

When inserting a complete row, the value of each field must appear. If a column has no value and the table allows the column to be null, the NULL value is used. The column values ​​must be populated in the order in which they appear in the table definition.

If a column is automatically grown, then MySQL will fill in the value after the automatic growth when NULL is filled.

The above form of statement is not safe and highly depends on the definition order of the columns in the table. The SQL must be rewritten after the next table structure change.

A safer way to write:

INSERT INTO tableName(fieldList)
VALUES(fieldValueList);

The order of the field values ​​of this writing method should be consistent with the order of the fields. Its advantage is that even if the structure of the table changes, the insert can work correctly. This way of writing does not need to have an auto-increment column, it can auto-increment without a value.

The second way of using column lists should always be used, it is safer.

When inserting data using a list of columns, some columns can be omitted:
1. Columns that allow NULL.
2. Columns with default values.

INSERT operation may be time-consuming (especially when many indexes need to be updated). If data retrieval is the most important, the priority of INSERT statement can be lowered, so that other requests (such as data retrieval) will be processed first when multiple requests come:

INSERT LOW_PRIORITY INTO

This also applies to UPDATE and DELETE statements.

Insert multiple pieces of data:

INSERT INTO tableName(fieldList)
VALUES(fieldValueList1),(fieldValueList2);

Processing multiple inserts with a single INSERT statement is faster than using multiple INSERT statements.

Read rows from a table and insert them into another table:

INSERT INTO tableName1(fieldList1)
SELECT fieldList2 
FROM tableName2;    # 还可添加WHERE过滤数据

The column values ​​in the retrieved fieldList2 are matched to the columns in fieldList1 in order. The matching column names in fieldList1 and fieldList2 are not necessarily the same.

Guess you like

Origin blog.csdn.net/tus00000/article/details/111404627