通过INSERT可以实现数据的插入,插入的方式分以下几种:
- 插入完成的行
- 插入行的一部分
- 插入多行
- 插入某些查询的结果
1. 插入完整的行
INSERT INTO customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
VALUES('Michael Jordan',
'100 Main Street',
'Los Angeles',
'CA',
'90000',
'USA',
NULL,
NULL);
mysq将用VALUES列表中的相应值填入列表中的对应项。VALUES的第一个值对应第一个指定的列名,第二个值对应第二个列名,以此类推。
这样做的好处是,每一个值对应一个列名,只要对应关系对,顺序不会影响结果。
此外,如果表的定义允许,可以在INSERT操作中省略某些列。省略的列必须满足以下条件。
- 该列定义为允许NULL值(无值或空值)
- 在表定义中给出默认值。如果不给出值,使用默认值
对于INSERT的一些优化
INSERT操作可能很耗时(特别是有很多索引需要更新时),而且可能降低等待处理的SELECT语句的特性。
可以通过在INSERT和INTO之间添加关键字LOW_PRIORITY,指示mysql降低INSERT语句的优先级,如下所示:
INSERT LOW_PRIORITY INTO
2. 插入多个行
如果插入的数据列名和次序相同可以使用如下语句:
INSERT INTO customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES(
'Jack Lee',
'100 Main Street',
'Los Angeles',
'CA',
'90001',
'USA'
),
(
'Martin Fuller',
'43 Galaxy Way',
'New York',
'NY',
'112233',
'USA'
);
如果插入的数据列名不同, 使用多条INSERT语句拼接
3. 插入检索出的数据
INSERT可以将一条SELECT语句的结果插入表中
INSERT INTO customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email)
SELECT cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country,
cust_contact,
cust_email
FROM custnew;