一、表的基本操作
1、数据库创建
CREATE DATABASE studentsdb;
2、使用数据库
USE studentsdb;
3、创建表
create table student_info
(学号 char(4) not null primary key,
姓名 char(8) not null,
性别 char(2),
出生日期 date,
家庭住址 varchar(50)
);
学号为该列属性名,char(4) 表示数据类型;not null 指定该属性值不能为null,primary key 指定该属性为主键
4、向表中插入数据
insert into student_info(学号,姓名,性别,出生日期,家庭住址)
values('0001','张青平','男','2000-10-01','衡阳市东凤路77号'),
('0002','刘东阳','男','1998-12-09','东阳市八一北路33号'),
('0003','马晓夏','女','1995-05-12','长岭市五一路763号'),
('0004','钱忠理','男','1994-09-23','滨海市洞庭大道279号'),
('0005','孙海洋','男','1995-04-03','长岛市解放路27号'),
('0006','郭小斌','男','1997-11-10','南山市红旗路113号'),
('0007','肖月玲','女','1996-12-07','东方市南京路11号'),
('0008','张玲珑','女','1997-12-24','滨海市新建路97号');
插入数据类型须和创建中的数据类型相对应
5、显示表的结构
DESC student_info;
6、查看表中数据
select * from student_info;
7、将某一列数据置空
set sql_safe_updates = 0;
alter table curriculum
modify 课程名称 char(50) NULL;
update curriculum set 课程名称 = NULL;
modify设置该列值可为null,再用update设置值为null
利用modify将某列数据类型改变为decimal(5, 2):
alter table grade modify 分数 decimal(5,2);
8、为表添加列
添加名为 备注,数据类型为 varchar(50) 的列
alter table student_info
add 备注 varchar(50);
9、删除表中的列
alter table curriculum
drop 学分;
10、创建数据库studb并使其中表stu结构与数据和studentdb的student_info表相同
create database studb;
use studb;
create table stu
select * from studentsdb.student_info;
11、删除表中数据
删除表curriculum中课程编号为0001的数据
delete from curriculum
where 课程编号=0001;
12、更新表中数据
update curriculum set 课程名称 = '数据库原理及应用'
where 课程编号 = '0003';
13、删除表
drop table curriculum;
14、删除数据库
drop database user_message;
二、视图
建立视图v_stu_c :
create view v_stu_c
as select 学号,姓名,课程编号 from student_info,curriculum;
查询学号为0003的学生情况:
select * from v_stu_c
where 学号=0003;
基于student_info表、curriculum表和grade表,建立一个名为v_stu_g的视图,视图包括所有学生的学号、姓名、课程名称、分数:
create view v_stu_g
as select student_info.学号, 姓名, 课程名称,分数 from student_info, grade where grade.学号 = student_info.学号 and grade.课程编号 = curriculum.课程编号;
通过使用where添加筛选条件防止多次选择数据
查询学号为0002的学生的课程平均分:
select * from v_stu_g;
select avg(分数) from v_stu_g
where 学号=0002;
修改视图v_stu_g, 显示学生的学号、姓名、性别:
alter view v_stu_g
as select 学号,姓名,性别 from student_info;
利用视图v_stu_g为student_info表添加一行数据:学号为0010、姓名为陈婷婷、性别为女:
insert into v_stu_g values('0010','陈婷婷','女');