1、查看所有数据库
show databases;

image.png
2、创建一个名为test的数据库
create database test;

image.png
3、选择需要操作的数据库,比如test
use test;
并不需要关键字database

image.png
4、创建一个名为student的表
create table student(
sno char(9) primary key, //设置sno为主键
sname char(20) unique, //设置sname取唯一值
ssex char(2),
sage smallint,
sdept char(20)
);
create table course(
cno char(4) primary key,
cname char(40) not null, //设置cname字段不能为空,列级完整性约束条件
cpno char(4), //cpno 表示先修课
ccredit smallint,
//参照表和被参照表可以是同一张表
foreign key (cpno) references course(cno) // 表级完整性约束条件,cpno是外码,被参照的表是course,被参照的列是cno
);
create table sc(
sno char(9),
cno char(4),
grade smallint,
primary key (sno,cno),
foreign key(sno) references student(sno),
foreign key(cno) references course(cno)
);

image.png
5、查看表结构
desc student;

image.png
6、向student表增加“入学时间”列,其数据类型为日期型
alter table student add s_entrance date;

image.png
7、将年龄的数据类型改为整型
alter table student change sage sage int; //第一种修改方式 alter table 表名称 change 字段原名称 字段新名称 字段类型 [是否允许非空]
alter table student modify sage smallint; //第二种修改方式
第一种方式可以修改列名

image.png

image.png
8、增加课程名称必须取唯一值的约束条件
alter table course add unique(cname);

image.png
9、删除表
drop table student [restrict]; //默认是restrict删除,即删除是有限制条件的。
在mysql中添加restrict或是cascade,则欲删除的表不能被其他表的约束所引用(如check,foreign key 等约束),不能有视图,不能有触发器,不能有存储过程或函数等。如果存在这些依赖该表的对象,则此表不能被删除。

image.png

image.png
10、建立索引
create unique index stusno on student(sno); //unique 表明此索引的每一个索引值只对应唯一的数据记录
create unique index coucno on course(cno);
create unique index scno on sc(sno asc, cno desc); //asc 升序排列,desc 降序排列

image.png
11、删除索引
alter table student drop index stusno;

image.png
12、修改索引
alter table sc rename index scno to scsno;

image.png
13、查看所有表
show tables;

image.png