0%

《MySQL必知必会》读书笔记 第十九章 插入数据

数据插入

使用INSERT来插入行到数据库表中。插入可以用几种方式使用:

  • 插入完整的行;
  • 插入行的一部分;
  • 插入多行;
  • 插入某些查询的结果。

插入完整的行

1
2
3
4
5
6
7
8
9
10
INSERT INTO Customers
VALUES(NULL,
'Pep E. LaPew',
'100 Main Street',
'Los Angeles',
'CA',
'90046',
'USA',
NULL,
NULL);

各个列必须以它们在表定义中出现的次序填充。

第一列cust_id也为NULL。这是因为每次插入一个新行时,该列由MySQL自动增量。

虽然这种语法很简单,但并不安全,应该尽量避免使用。上面的SQL语句高度依赖于表中列的定义次序。

编写INSERT语句的更安全的方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
INSERT INTO Customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
VALUES('Pep E. LaPew',
'100 Main Street',
'Los Angeles',
'CA',
'90046',
'USA',
NULL,
NULL);

因为提供了列名,VALUES必须以其指定的次序匹配指定的列名,不一定按各个列出现在实际表中的次序。其优点是,即使表的结构改变,此INSERT语句仍然能正确工作。

使用这种语法,还可以省略列。省略的列必须满足以下某个条件:

  • 该列定义为允许NULL值。
  • 在表定义中给出默认值。则表示如果不给出值,将使用默认值。

插入多个行

可以使用多条INSERT语句,或者一条INSERT语句中列出多行数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
INSERT INTO Customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES(
'Pep E. LaPew',
'100 Main Street',
'Los Angeles',
'CA',
'90046',
'USA'
),
(
'M. Martian',
'42 Galaxy Way',
'New York',
'NY',
'11213',
'USA'
);

此技术可以提高数据库处理的性能,因为MySQL用单条INSERT语句处理多个插入比使用多条INSERT语句快。

插入检索出的数据

INSERT还存在另一种形式,可以利用它将一条SELECT语句的结果插入表中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
INSERT INTO customers(cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
SELECT cust_id,
cust_contact,
cust_email,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country
FROM custnew;

可以省略cust_id,这样MySQL会生成新值。

不一定要求列名匹配,该语句是按照位置填充的。

INSERT SELECT中SELECT语句可包含WHERE子句以过滤插入的数据。