Mysql第八章小结--插入,更新与删除数据

目录

  • 插入数据
  • 更新数据
  • 删除数据

插入数据

先建立一个表

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

指定所有列的插入

#插入数据
insert into person(id,name,age,info) 
values (1,'Green',21,'Lawyer');

不指定的直接插入

#允许直接插入,不指定字段,但是每一条都要有
insert into person
values(2,'Suse',22,'dancer'),
(3,'Mary',24,'Musician');

这里写图片描述


没有指定的列,如果设置了自增,就自增,如果有默认值,就插入默认值。

#没有指定第一列
insert into person(name,age,info) #只指定了三列
values 
('Willam',20,'sports man');

这里写图片描述

#没有指定,使用默认值
insert into person(name,age) 
values ('Laura',25); #info列为null(默认)

注意insert插入多个记录时的一些注意事项:
这里写图片描述


将查询结果插入到表中

可以将一个查询的结果插入到另一个表中

#测试将查询结果插入到表中
create table person_old
(
    id int unsigned not null auto_increment,
    name char(40) not null default '',
    age int not null default 0,
    info char(50) null,
    primary key(id)
);

insert into person_old
values(11,'Harry',20,'student'),
(12,'Beckham',31,'police');

select * from person_old;
select * from person;

insert into person(id,name,age,info)
(select id,name,age,info from person_old);

这里写图片描述
这里写图片描述


更新数据

更新数据操作很简单,主要是要记得条件

#更新数据
update person set age = 15,name = 'LiMing' 
where id = 11;

删除数据

#删除数据
delete * from person where id = 11;

#删除数据表中所有的数据
delete from person;

#注意删除数据时一定要小心

猜你喜欢

转载自blog.csdn.net/zxzxzx0119/article/details/80056880