在本教程中,我们将学习如何使用sql insert
语句来将数据插入表中。
sql提供了insert
语句,用于将一行或多行插入表中。 insert
语句用于:
我们将在以下部分中来看看insert
语句的每个用法。
要向表中插入一行,请使用insert
语句的以下语法。
insert into table1 (column1, column2,...)
values
(value1, value2,...);
在表中插入新行时,应注意以下几点:
首先,值的数量必须与列数相同。 此外,列和值必须是对应的,因为数据库系统将通过它们在列表中的相对位置来匹配它们。
其次,在添加新行之前,数据库系统检查所有完整性约束,例如,外键约束,主键约束,检查约束和非空约束。如果违反了其中一个约束,数据库系统将发出错误并终止语句,而不向表中插入任何新行。
如果值序列与表中列的顺序匹配,则无需指定列。 请参阅以下insert
语句,该语句省略insert into
子句中的列列表。
insert into table1
values
(value1, value2,...);
但是,这不是一个好的做法。
如果在插入新行时未在insert
语句中指定列及其值,则列将采用表结构中指定的默认值。 默认值可以是0
,序列中的下一个整数值,当前时间,null
值等。请参阅以下语句:
insert into (column1, column3)
values
(column1, column3);
在此语法中,column2
将采用默认值。
我们将使用示例数据库中的employees
和dependents
表来演示如何向表中插入一行。
要在dependents
表中插入新行。参考以下语句 -
insert into dependents (
first_name,
last_name,
relationship,
employee_id
)values('max','su','child',176);
我们没有在insert
语句中使用department_i
d列,因为dependent_id
列是自动增量列,因此,当插入新行时,数据库系统使用下一个整数作为默认值。
employee_id
列是将dependents
表链接到employees
表的外键。 在添加新行之前,数据库系统会检查employees
表的employee_id
列中是否存在值:176
,以确保不违反外键约束。
如果成功插入行,则数据库系统返回受影响的行数。
可以使用以下select
语句检查是否已成功插入行。
select
*
from
dependents
where
employee_id = 176;
执行上面查询语句,得到以下结果 -
+--------------+------------+-----------+--------------+-------------+
| dependent_id | first_name | last_name | relationship | employee_id |
+--------------+------------+-----------+--------------+-------------+
| 31 | max | su | child | 176 |
+--------------+------------+-----------+--------------+-------------+
1 rows in set
要使用单个insert
语句插入多行,请使用以下构造:
insert into table1
values
(value1, value2,...),
(value1, value2,...),
(value1, value2,...),
...;
例如,要在dependents
表中插入两行,请使用以下查询。
insert into dependents (
first_name,
last_name,
relationship,
employee_id
)
values
(
'avg',
'lee',
'child',
192
),
(
'michelle',
'lee',
'child',
192
);
数据库系统返回2
行受影响,可以使用以下语句验证结果。
select
*
from
dependents
where
employee_id = 192;
可以使用insert
语句查询来自一个或多个表的数据,并将其插入另一个表中,如下所示:
insert into table1 (column1, column2)
select
column1,
column2
from
table2
where
condition1;
在此语法中,使用select
(称为子选择)而不是values
子句。 子选择可以包含连接,以便可以组合来自多个表的数据。 执行语句时,数据库系统在插入数据之前首先评估子选择。
假设有一个名为dependents_archive
的表,其结构与dependents
表具有相同的结构。 以下语句将dependents
表中的所有行复制到dependents_archive
表中。
insert into dependents_archive
select
*
from
dependents;
您可以使用以下语句验证插入操作是否成功 -
select
*
from
dependents_archive;
通过上面的示例学习,我们已经知道如何使用sql insert
语句将一行或多行插入表中。