数据库复试-SQL数据定义与数据查询语句
使用mysql数据库代替之前的sqlserver (完全使用命令行进行操作)
一:登录数据库登录与创建
mysql -uroot -p
123456
CREATE TABLE Student(
Sno CHAR(9) PRIMARY KEY, /*主键约束*/
Sname CHAR(20) UNIQUE, /*唯一值*/
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20)
);
-- 选课表
CREATE TABLE Course(
Cno CHAR(4) PRIMARY KEY,
Cname CHAR(40) NOT NULL,
Cpno CHAR(4),
Ccredit SMALLINT,
FOREIGN KEY(Cpno) REFERENCES 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),
);
查询数据插入
使用插入—数据更新语句向创建的表中插入数据
insert into Student(Sno,Sname,Ssex,Sage,Sdept)values('','','','','');
insert into Student(Sno,Sname,Ssex,Sage,Sdept)values('201215121','李勇','男','20','CS');
insert into Student(Sno,Sname,Ssex,Sage,Sdept)values('201215122','刘晨','女','19','IS');
insert into Student(Sno,Sname,Ssex,Sage,Sdept)values('201215123','王敏','女','18','MA');
insert into Student(Sno,Sname,Ssex,Sage,Sdept)values('20121515','张立','男','19','IS');
课程表数据插入
由于外键引用主键注意插入的顺序
insert into course(Cno,Cname,Ccredit)values('2','数学','2');
insert into course(Cno,Cname,Ccredit)values('6','数据处理','2');
insert into course(Cno,Cname,Cpno,Ccredit)values('4','操作系统','6','3');
insert into course(Cno,Cname,Cpno,Ccredit)values('7','PASCAL语言','6','4');
insert into course(Cno,Cname,Cpno,Ccredit)values('5','数据结构','4','4');
insert into course(Cno,Cname,Cpno,Ccredit)values('1','数据库','5','4');
insert into course(Cno,Cname,Cpno,Ccredit)values('3','信息系统','1','4');
选课表(中间表或联系表)数据插入
insert into sc(Sno,Cno,Grade)values('201215121','1',92);
insert into sc(Sno,Cno,Grade)values('201215121','2',85);
insert into sc(Sno,Cno,Grade)values('201215121','3',88);
insert into sc(Sno,Cno,Grade)values('201215122','2',90);
insert into sc(Sno,Cno,Grade)values('201215122','3',80);
此时创建表的基本信息插入完成
SQL核心查询操作
单表查询选择表中的若干列
select sno,sname from student;
select sno,sname,sdept from student;
使用计算式
select sno,2014-sage from student;
列名使用别名进行代替(添加指定列)
select Sname Name,'years-of-birth' Birth,2014-sage Birthday,Sdept Department from student;
选择若干元组进行去重操作(distinct)
select distinct sno from sc;
条件查询或逻辑查询(where)
基于编程语言中的逻辑运算符与关键字进行操作
只对部分关键字进行回忆
- between and
- not null
- like
- in
- not
- and
- or
等常用的关键字
实验举例
查询年纪在20岁以下的学生姓名和年龄
select sname,sage from student where sage<20;
查询考试成绩不及格的学生学号
select distinct sno from sc where grade<60;
多表查询举例
查询哪些学生的哪一门成绩低于90分
select sname,cname,grade from student,course,sc where grade<90 and sc.sno=student.sno and sc.cno=course.cno;