Note/数据库导论/笔记/数据库笔记04——插入数据——2022-03-15.md

5.2 KiB
Raw Blame History

实机操作

进入名为 sys 数据库

use sys;

创建表 person

create table person(
 id int not null primary key auto_increment,
 name char(40) not null default '',
 age int not null default 20,
 info char(5) null
 );

查看数据

desc person;

image-20220315081824424

查看表内数据

select * from person;

image-20220315082028785

插入数据

insert into person (id,name,age,info)
values(1,'Green',21,'lar');

查看数据

image-20220315082524826

插入数据

insert into person (id,age,name,info) values(2,22,'su','do');

查看数据

image-20220315082918594

插入数据

insert into person values(3,'wang',23,'ji');

查看数据

image-20220315083226414

插入数据

insert into person (age,name,info) values(32,'xu','deo');

查看数据

image-20220315083745218

插入指定字段

insert into person (age,name,info) values(32,'xu','deo');
insert into person (name,age)values('wan',23);
insert into person (name)values('win');

image-20220315084255104

插入多条数据

insert into person (age,name,info)
values(26,'xi','dreo'),
(22,'ju','do'),
(39,'vheng','dxu');

image-20220315085241890

创建新表

create table person2(
 id int not null primary key auto_increment,
 name char(40) not null default '',
 age int not null default 20,
 info2 char(5) null
 );

将查询结果插入到表中

insert into person2 (id,name,age,info2)
select * from person;

image-20220315090756156

更新数据

 update person set age=15,name='liming' where id=9;

image-20220315092323856

查询语句限制

select * from person where id=9;
*是指泛指
select name from person where id=9;

image-20220315092608371

image-20220315092645199

查询年龄在19到25之间的人

select * from person where age between 19 and 25;

image-20220315092906118

删除表中 id 为9的人

delete from person where id=9;

image-20220315093201546

删除所有表中数据

delete from person;

image-20220315093559445

一、插入数据

1.为表的所有字段插入数据

insert into 表名 (字段名,字段名,字段名)
values(对应字段的值,对应字段的值,对应字段的值);

备注:允许字段名顺序与建表时顺序不同,不需要按照表定义的顺序插入,只要保证值的顺序和前面字段名的顺序相同即可。

insert into person (id,age,name,info) values(2,22,'su','do');

备注2使用insert语句插入数据时允许将字段名省略此时注意值列类表需要为表中的每一个字段赋值并且值的顺序必须与建表时各个字段的顺序相同。

insert into person (id,age,name,info) values(2,22,'su','do');

2.为表指定字段插入数据

为表的指定字段插入数据,就是在 insert 语句中指向部分字段插入值,而其他字段的值为表定义时的默认值。

insert into person (age,name,info) values(32,'xu','deo');

insert into person (name,age)values('wan',23);

insert into person (name)values('win');

备注:要保证每个插入值的类型和对应字段的数据类型保持一致,否则报错

3.同时插入多条数据

insert into 表名 (各个字段名) values(第一条记录的值列表), (第二条记录的值列表), (第三条记录的值列表)

例:

insert into person (age,name,info)
values(26,'xi','dreo'),
(22,'ju','do'),
(39,'vheng','dxu');

4.将查询结果插入到表中

语法insert into 新表名(字段名)查询语句;此处没有values

注意:两个表的数据类型必须一致,字段个数也要一致。

insert into person2 (id,name,age,info2)select * from person;

二、更新数据

update 表名 set 需要更新字段名1=值,需要更新的字段名2=值 where 条件;

补充select 字段名 from 表名 where 条件;

select * from person where age between 19 and 25;

三、删除数据(删除操作是不可逆的删除时一点要小心)

1.有选择删除

语法delete from 表名 where 限定条件;

delete from person where id=9;

2.删除表中所有数据

语法delete from 表名;