创建班级表:
mysql> create table class1( -> cid int auto_increment primary key, -> caption varchar(32) not null default '' -> )charset=utf8; insert into class1 (caption) values ('三年二班'),('一年三班'),('三年一班'); mysql> select * from class1; +-----+--------------+ | cid | caption | +-----+--------------+ | 1 | 三年二班 | | 2 | 一年三班 | | 3 | 三年一班 | +-----+--------------+ 3 rows in set (0.00 sec)
创建学生表:
mysql> create table stu( -> sid int auto_increment primary key, -> sname varchar(32) not null default '', -> gender varchar(32) not null default '', -> class_id int not null default 1, -> -> constraint fk_stu_class1 foreign key (class_id) references class1(cid) -> )charset=utf8; mysql> insert into stu (sname, gender, class_id) values ('钢蛋','女',1),('铁锤','女',1),('山炮','男',2); mysql> select * from stu; +-----+--------+--------+----------+ | sid | sname | gender | class_id | +-----+--------+--------+----------+ | 1 | 钢蛋 | 女 | 1 | | 2 | 铁锤 | 女 | 1 | | 3 | 山炮 | 男 | 2 | +-----+--------+--------+----------+ 3 rows in set (0.00 sec)
创建老师表:
mysql> create table tea( -> tid int auto_increment primary key, -> tname varchar(32) not null default '' -> )charset=utf8; insert into tea (tname) values ('Allen'),('Frank'),('Julie'); mysql> select * from tea; +-----+-------+ | tid | tname | +-----+-------+ | 1 | Allen | | 2 | Frank | | 3 | Julie | +-----+-------+ 3 rows in set (0.00 sec)
创建课程表:
mysql> create table cour( -> cid int auto_increment primary key, -> cname varchar(32) not null default '', -> tea_id int not null default 1, -> -> constraint fk_cour_tea foreign key (tea_id) references tea(tid) -> )charset=utf8; insert into cour (cname, tea_id) values ('生物',1),('体育',1),('物理',2); mysql> select * from cour; +-----+--------+--------+ | cid | cname | tea_id | +-----+--------+--------+ | 1 | 生物 | 1 | | 2 | 体育 | 1 | | 3 | 物理 | 2 | +-----+--------+--------+ 3 rows in set (0.00 sec)
成绩表:
mysql> create table sco( -> sid int auto_increment primary key, -> stu_id int not null default 1, -> cou_id int not null default 0, -> number int not null default 0, -> constraint fk_sco_stu foreign key (stu_id) references stu(sid), -> constraint fk_sco_cour foreign key (cou_id) references cour(cid) -> )charset utf8; mysql> insert into sco (stu_id, cou_id, number) values (1,1,60),(1,2,59),(2,2,100); mysql> select * from sco; +-----+--------+--------+--------+ | sid | stu_id | cou_id | number | +-----+--------+--------+--------+ | 1 | 1 | 1 | 60 | | 2 | 1 | 2 | 59 | | 3 | 2 | 2 | 100 | +-----+--------+--------+--------+ 3 rows in set (0.00 sec)
--1、查询所有大于60分的学生的姓名和学号 (DISTINCT: 去重)
mysql> select distinct stu.sid,stu.sname from sco left join stu on stu.sid=stu_id where number>=60; +------+--------+ | sid | sname | +------+--------+ | 1 | 钢蛋 | | 2 | 铁锤 | +------+--------+ 2 rows in set (0.01 sec)