Note/数据库导论/试题/综合案例2-记录的插入、更新和删除.md

6.3 KiB
Raw Blame History

综合案例2-记录的插入、更新和删除

本部分内容重点介绍了数据表中数据的插入、更新和删除操作。MySQL中可以灵活的对数据进行插入与更新MySQL中对数据的操作没有任何提示因此在更新和删除数据时一定要谨慎小心查询条件一定要准确避免造成数据的丢失。此综合案例包含了对数据表中数据的基本操作包括记录的插入、更新和删除。

1、案例目的

创建表books对数据表进行插入、更新和删除操作掌握表数据的基本操作。books表结构以及表中的记录如表1和表2所示

表1 books表结构

字段名 数据类型 主键 外键 非空 唯一 自增 字段说明
b_id int11 书编号
b_name varchar50 书名
authors varchar100 作者
price float 价格
pubdate year 出版日期
note varchar100 说明
num int11 库存量

表2 books表中的记录

b_id b_name authors price pubdate note num
1 Tale of AAA Dickes 23 1995 novel 11
2 EmmaT Jane lura 35 1993 joke 22
3 Story of Jane Jane Tim 40 2001 novel 0
4 Lovey Day George Byron 20 2005 novel 30
5 Old Land Honore Blade 30 2010 law 0
6 The Battle Upton Sara 30 1999 medicine 40
7 Rose Hood Richard Haggard 28 2008 cartoon 28

2、案例操作过程

1登录MySQL数据库。

mysql -h localhost -u root -p

截图:

img

2创建数据库M_BOOK并选择使用此数据库。

create database M_BOOK;
desc M_BOOK;

截图:

image-20220315141208398

3按照表1创建表books创建成功后用desc查看表结构。

create table books(
	b_id int(11) not null unique,
	b_name varchar(50) not null,
	authors varchar(100) not null,
    price float not null,
    pubdate year not null unique,
    note varchar(100) null,
    num int(11) not null,
    primary key(b_id)
);

截图:

image-20220315142332615

4使用select语句查询表中的数据此处查询结果应为空

select * from books;

截图:

image-20220315142310880

5将表2中的记录插入到books表中分别使用不同的方法插入记录。

①指定所有字段名插入第1行记录插入后用select语句查询插入结果

insert into books (b_id,b_name,authors,price,pubdate,note,num) values(1,'Tale of AAA','DIckes',23,1995,'novel',11);
select * from books;

截图:

image-20220315142912049

②不指定字段名插入第2行记录插入后用select语句查询插入结果

insert into books values(2,'EmmaT','Jane lura',35,1993,'joke',22);
select * from books;

截图:

image-20220315143315288

③同时插入第3~7行记录插入后用select语句查询插入结果

insert into books (b_id,b_name,authors,price,pubdate,note,num)
values (3,'Story of Jane','Jane Tim',40,2001,'novel',0),
(4,'Lovey Day','George Byron',20,2005,'novel',30),
(5,'Old Land','Honore Blade',30,2010,'law',0),
(6,'The Battle','Upton Sara',30,1999,'medicine',40),
(7,'Rose Hood','Richard Haggard',28,2008,'cartoon',28);

截图:

image-20220315144009242

6使用select语句查询小说类型novel的书的所有信息。

select * from books where note='novel';

截图:

image-20220315144355595

7将小说类型novel的书的价格都增加5并在更新后使用select语句查询小说类型novel的书的所有信息

update books set  price=price+5 where note='novel';
select * from books where note='novel';

截图:

image-20220315145957535

8使用select语句查看书名为EmmaT的信息

select * from books where b_name='EmmaT';

截图:

image-20220315150138907

9将名为EmmaT的书价格改为40并使用select语句查询更新后的该书信息。

update books set  price=40 where b_name='EmmaT';
select * from books where b_name='EmmaT';

截图:

image-20220315150252053

10查询库存量为0的书的所有信息。

select * from books where num=0;

截图:

image-20220315150322666

11删除库存量为0的书的所有信息并使用select语句查询库存量为0的书的所有信息此处应为空

delete from books where num=0;
select * from books where num=0;

截图:

image-20220315150431488