这一节将讲述如何使用 INSERT 插入数据

数据插入

顾名思义, INSERT 用来将行插入(或添加)到数据库表,插入有几种方式:

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

插入完整的行

插入完整的行,可以不指定字段名,靠次序来定位,也可以指定字段名,这样可以更安全(也允许乱序)

  • 不指定字段名(不推荐)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    INSERT INTO Customers # 这个 INTO 在某些 DBMS 是可以选的,但还是建议加上
    VALUES(1000000006,
    'Toy Land',
    '123 Any Street',
    'New York',
    'NY',
    '11111',
    'USA',
    NULL,
    NULL);
  • 指定字段名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    INSERT INTO Customers(cust_id,
    cust_name,
    cust_address,
    cust_city,
    cust_state,
    cust_zip,
    cust_country,
    cust_contact,
    cust_email)
    VALUES(1000000006,
    'Toy Land',
    '123 Any Street',
    'New York',
    'NY',
    '11111',
    'USA',
    NULL,
    NULL);

    (因为主键是不能重复的,所以你不能插入两次)

插入部分行

指定列名时,如果表允许的话,可以省略部分列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
INSERT INTO Customers(cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES(1000000006,
'Toy Land',
'123 Any Street',
'New York',
'NY',
'11111',
'USA');

如果省略,则会被填入默认值或 NULL 值,如果表没有设定默认值又不允许 NULL 值,就会报错

插入检索出的数据

使用 INSERT SELECT ,可以向表中插入检索的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
INSERT INTO Customers(cust_id,
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
SELECT cust_id, # 其实这里的列名没必要与上面的相同,只是按顺序对号入座而已
cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country
FROM CustNew # 不存在这张表,只是示例

一般来说 INSERT 只会插入一行,但是 INSERT SELECT 会把检索的所有结果都插入