Insert data-INSERT

As the name implies, INSERT is used to insert rows into database tables

Insertion can be used in several ways:

  1. Insert complete row
  2. Insert part of a row
  3. Insert multiple rows
  4. Insert some query results

 

One, insert a complete line

INSERT INTO customers
VALUES
(
     NULL,
	'pep',
	'100 Street',
	'Los Angles',
	'CA',
	'90046',
	'USA',
	NULL,
    NULL
)

Analysis: This example inserts a new customer into the customers table. If a column has no value, NULL should be used (the table allows the value to be empty), and the first column cust_id is also NULL, because this is an automatic increment

 

The above syntax is very simple, but it is not safe, because it is highly dependent on the order in which the columns in the table are defined, and there is no guarantee that the order after the next table structure change will be the same.

Let's change the INSERT statement to make it safer.

INSERT INTO customers
(
  cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zip,
	cust_country,
	cust_contact,
	cust_email
)
VALUES
(
	'pep',
	'100 Street',
	'Los Angles',
	'CA',
	'90046',
	 'USA',
	 NULL,
	 NULL
)

Analysis: We have given a clear column name, only need to ensure that the value corresponds to it when inserting. And the order of the column can be different from the order defined in the table

Omission of columns:

  1. The column is defined to allow NULL values ​​(no value or null value)
  2. The column definition gives the default value
  3. If a column that is NULL and has no default value is not allowed in the table, and no value is given when inserting, an error will be reported

 

Second, insert multiple rows

Each set of values ​​is enclosed in parentheses and separated by commas. This technique can improve the performance of database processing because a single statement executes faster than multiple statements.

INSERT INTO customers
(
  cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zip,
	cust_country
)
VALUES
(
	'pep',
	'100 Street',
	'Los Angles',
	'CA',
	'90046',
	 'USA'
),
(
	'aaa',
	'31 Street',
	'New York',
	'NY',
	'11232',
	'CHINA'
);

 

3. Insert the retrieved data

Add the data you want to insert from one table to another, you can use the insert query INSERT SELECT.

INSERT INTO customers
(
    cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zip,
	cust_country
)
SELECT 
    cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zip,
	cust_country
FROM custnew;

This example uses INSERT SELECT to insert all data from custnew to customers.

MySQL does not care about the column names returned by SELECT, so the first column value of SELECT will be used to fill the first column specified in INSERT. This is very useful for importing data from tables with different column names.

Published 156 original articles · Liked 34 · Visits 150,000+

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105572734