学习重点
- insert 原则上每次执行一行数据插入。
- 对表中所有列进行insert 操作时可以省略表明后的列清单。
- 插入NULL时需要在VALUES子句的值清单中写入NULL。
- 可以为表中的列设置默认值(初始值)。默认值可以通过在create table语句中,为列设置default约束来设定。
- 插入默认值方法有两种:
①create table … default…
②insert 。。。values。。。default。。。
使用insert…select 可以从其他表中复制数据
insert 语句的基本语法
insert into 表明(声明要插入数据的列名) values(对应列的值,对应列的值,对应列的值,);
举例:
insert into table (name,age)
values
('Tom',22);
#表内列有 name,age,sex
#如果插入值为表全列可以直接省略列名强调
insert into table
values
('Tom',22,'男');
插入NULL
插入null的前提是 默认值(default)设置不能为 NOT NULL,否则会数据插入失败。
实例:
insert into table
values
('Tom',22,NULL);
插入默认值
创建表时插入默认值
create table student(
name varchar(10) NOT NULL, ## 默认设置内容不能为NULL
age int,
sex varchar(2) default '女' ## 默认值为女
);
insert 插入默认值 两种使用方法
显示方法插入默认值
insert into student
values
('jack',25,default); ## 这里的default 会自动设置为他的默认值 女 (即使jack 是个男性)
隐示方法插入默认值
insert into student(name,age)
values
('jack',25); ## 声明插入表时忽略sex,插入数据是也不插入sex值,此时sex便自动生成插入默认值
从其他表中复制数据
继承上面所强调的,现在有表student,里面有一条数据:
现在复制一个student 表名为studentcopy,结构与student一致,
create table studentcopy(
name varchar(10) NOT NULL,
age int,
sex varchar(2) default '女'
);
现在向studentcopy中插入student的数据
insert into studentcopy
select * from student;
#向studentcopy插入student中的全部数据
其中多种多样的select 语句都可以使用
insert语句中的select语句,可以使用where或者group by等任何SQL语法。