数据库练习:DQL,约束,视图,触发器

-- 准备工作,建库,切库
CREATE DATABASE IF NOT EXISTS lx CHARSET 'UTF8';
USE lx;
-- 1、创建persons表,id设置为主键,表的格式(id integer primary key,name
text,addr text,class text)
CREATE TABLE person(
    id integer primary key auto_increment,
    name text,
    addr text,
    class text
);
-- 2、创建grade表,设置约束条件(score>0),表的格式(id integer, score
integer, year text)
create table grade(
    id integer, score integer, year text
);
-- 3、追加相应的数据,见下页
insert into person (name, addr, class) value('lucy','beijing','class_A');
insert into person (name, addr, class) value('peter','tianjing','class_B');
insert into person (name, addr, class) value('bob','hebei','class_A');
insert into grade (id, score, year) value (1,78,'2013');
insert into grade (id, score, year) value (2,98,'2013');
insert into grade (id, score, year) value (3,80,'2013');
insert into grade (id, score, year) value (1,88,'2014');
-- 4、打印所有学生的信息:包括name,addr,class,score,year
select p.*,g.score,g.year from person p,grade g where p.id = g.id;
-- 5、将打印所以学生信息的语句,创建视图PersonsGrade,方便后面使用
create view persongrade as select p.*,g.score,g.year from person
p,grade g where p.id = g.id;
-- 6、查看最高分数是多少?
select max(score) from persongrade;
-- 7、查看每个班的平均分,以及对应的班级名称和班级人数
select class 班级, count(distinct id) 人数, avg(score) from persongrade group by class;
-- 8、在persons表中id列创建一个索引persons_id_index
create index person_id_index on person (id);
-- 9、查看lucy在2013年的成绩
select * from persongrade where name='lucy' and year='2013';
-- 10、bob要退学,必须要删除bob所有的信息(包括成绩单),通过设置触发器,自动
删除bob相关的所有数据,设置触发器tg_delete
delimiter ||
create trigger tg_delete after delete on person for each row
begin
    delete from grade where grade.id = old.id;
end ||
delimiter ;
-- 11、执行删除bob的操作
delete from person where name='bob';
-- 12、查看所有人的信息,确定是否执行了删除操作
select * from person;
select * from grade;
select * from persongrade;

你可能感兴趣的:(数据库,数据库,oracle,sql)