Note/大学笔记/数据库导论/试题/综合案例1——数据表的基本操作.md

5.9 KiB
Raw Blame History

综合案例1——数据表的基本操作

在全面介绍了MySQL中数据表的各种操作如创建表、添加各类约束查看表结构以及修改和删除表同学们应该掌握这些基本操作为以后的学习打下坚实的基础。在这里给出一个综合案例让同学们全面回顾一下本章的知识要点并通过这些操作来检验自己是否已经掌握了数据表的常用操作。

1、案例目的

创建、修改和删除表,掌握数据表的基本操作。

创建数据库company按照表1和表2给出的表结构在company数据库中创建两个数据表offices和employees按照操作过程完成对数据表的基本操作。

表1 offices表结构

字段名 数据类型 主键 外键 非空 唯一 自增
officecode int10
city int11
address varchar50
country varchar50
postalcode varchar25

表2 employees表结构

字段名 数据类型 主键 外键 非空 唯一 自增
employeenumber int11
lastname varchar50
firstname varchar50
mobile varchar25
officecode int10
jobtitle varchar50
birth datetime
note varchar255
sex varchar5

2、案例操作过程

1登录MySQL数据库。

mysql -h local -u root -p

截图:

img

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

create database company;

use company;

截图:

img

3创建表offices创建成功后用desc查看表结构。

create table offices(
    officecode int(10) not null unique primary key,
    city int(11) not null ,
    address varchar(50) null ,
    country varchar(50) not null,
    postalcode varchar(25) null unique
    );
    
desc offices;

截图:

img

4创建表employees创建成功后用desc查看表结构。

create table employees(
	employeenumber int(11) not null unique auto_increment primary key,
    lastname varchar(50) not null,
    firstname varchar(50) not null,
    mobile varchar(25) null unique,
    officecode int(10) not null ,
    birth datetime not null,
    note varchar(255) null,
    sex varchar(5) null,
    foreign key(officecode) references offices(officecode)
	);

截图:

image-20220308170243379

5使用show tables命令查看数据库中的表。

show tables	

截图:

image-20220308170414341

6将表employees的mobile字段修改到officecode字段后面成功后使用desc查看修改后的表结构。

alter table employees modify mobile varchar(25) after officecode;

desc employees;

截图:

image-20220308170720963

7将表employees的birth字段名改为employee_birth成功后使用desc查看修改后的表结构。

 alter table employees change birth employees_birth datetime;
 
 desc employees;

截图:

image-20220308171008325

8修改sex字段数据类型为char(1)非空约束成功后使用desc查看修改后的表结构。

alter table employees modify sex char(1) not null;

desc employees;

截图:

image-20220308171528384

9删除字段note成功后使用desc查看修改后的表结构。

alter table employees drop note;

desc employees;

截图:

image-20220308171326509

10增加字段名favoriate_activity数据类型为varchar(100) 成功后使用desc查看修改后的表结构。

alter table employees add favoriate_activity varchar(100);

desc employees;

截图:

image-20220308171746485

11删除表offices操作成功后用show tables查看数据库中的表。

drop table offices;

alter table employees drop foreign key employees_ibfk_1;

drop table offices;

show tables;

截图:

image-20220308172132982

12修改表employees存储引擎为myisam执行成功后用show create table语句查看表结构。

alter table employees engine = myisam;

show create table employees;

截图:

image-20220308172645359

13将表employees名称修改为employees_info执行成功后用show tables查看数据库中的表。

alter table employees rename employees_info;

show tables;

截图:

image-20220308172838692