MySQL武林秘籍,学废必过考试

前言

最近有很多大学僧网友以苦于逃课没有学习MySQL,到处看视频网站学习,没有体系化的只是体系,将曾经的Mysql实战案例分享给网友,相互学习,考试必过


1.建表语句

注:讲以下建表create_db.sql,导入Mysql数据库
mysqldump -uroot -p >d:/create_db.sql

-- MySQL dump 10.13  Distrib 5.7.21, for Win64 (x86_64)
--
-- Host: localhost    Database: db_school
-- ------------------------------------------------------
-- Server version	5.7.21-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `db_school`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `db_school` /*!40100 DEFAULT CHARACTER SET gb2312 */;

USE `db_school`;

--
-- Table structure for table `tb_class`
--

DROP TABLE IF EXISTS `tb_class`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_class` (
  `classNo` char(6) NOT NULL,
  `className` varchar(20) NOT NULL,
  `department` varchar(20) DEFAULT NULL,
  `grade` enum('1','2','3','4') DEFAULT NULL,
  `classNum` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`classNo`),
  UNIQUE KEY `uq_class` (`className`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tb_class`
--

LOCK TABLES `tb_class` WRITE;
/*!40000 ALTER TABLE `tb_class` DISABLE KEYS */;
INSERT INTO `tb_class` VALUES ('AC1301','会计13-1班','会计学院','1',35),('AC1302','会计13-2班','会计学院','1',35),('CS1401','计算机14-1班','计算机学院','2',35),('IS1301','信息系统13-1班','信息学院','1',NULL),('IS1401','信息系统14-1班','信息学院',NULL,30);
/*!40000 ALTER TABLE `tb_class` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tb_course`
--

DROP TABLE IF EXISTS `tb_course`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_course` (
  `courseNo` char(6) NOT NULL,
  `courseName` varchar(20) NOT NULL,
  `credit` decimal(3,1) NOT NULL,
  `courseHour` tinyint(2) NOT NULL,
  `term` tinyint(1) DEFAULT NULL,
  `priorCourse` char(6) DEFAULT NULL,
  PRIMARY KEY (`courseNo`),
  UNIQUE KEY `courseName` (`courseName`),
  UNIQUE KEY `uqidx_courseName` (`courseName`(3)),
  KEY `fk_course` (`priorCourse`),
  CONSTRAINT `fk_course` FOREIGN KEY (`priorCourse`) REFERENCES `tb_course` (`courseNo`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tb_course`
--

LOCK TABLES `tb_course` WRITE;
/*!40000 ALTER TABLE `tb_course` DISABLE KEYS */;
INSERT INTO `tb_course` VALUES ('11003','管理学',2.0,32,2,NULL),('11005','会计学',3.0,48,3,NULL),('21001','计算机基础',3.0,48,1,NULL),('21002','OFFICE高级应用',3.0,48,2,'21001'),('21004','程序设计',4.0,64,2,'21001'),('21005','数据库',4.0,64,5,'21004'),('21006','操作系统',4.0,64,5,'21001'),('31001','管理信息系统',3.0,48,3,'21004'),('31002','信息系统-分析与设计',2.0,32,4,'31001'),('31005','项目管理',3.0,48,5,'31001');
/*!40000 ALTER TABLE `tb_course` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tb_score`
--

DROP TABLE IF EXISTS `tb_score`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_score` (
  `studentNo` char(10) NOT NULL,
  `courseNo` char(6) NOT NULL,
  `score` decimal(4,1) NOT NULL,
  PRIMARY KEY (`studentNo`,`courseNo`),
  KEY `idx_stuNo_courNo` (`courseNo`,`studentNo`),
  KEY `idx_courseNo` (`courseNo`),
  CONSTRAINT `fk_score_courNo` FOREIGN KEY (`courseNo`) REFERENCES `tb_course` (`courseNo`),
  CONSTRAINT `fk_score_stuNo` FOREIGN KEY (`studentNo`) REFERENCES `tb_student` (`studentNo`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tb_score`
--

LOCK TABLES `tb_score` WRITE;
/*!40000 ALTER TABLE `tb_score` DISABLE KEYS */;
INSERT INTO `tb_score` VALUES ('2013110101','11003',90.0),('2013110101','21001',86.0),('2013110103','11003',89.0),('2013110103','21001',88.0),('2013110201','11003',78.0),('2013110201','21001',92.0),('2013110202','11003',82.0),('2013110202','21001',85.0),('2013310101','21004',83.0),('2013310101','31002',68.0),('2013310103','21004',80.0),('2013310103','31002',76.0),('2014210101','11003',80.0),('2014210101','11005',75.0),('2014210101','21001',60.0),('2014210101','21002',93.0),('2014210101','21004',89.0),('2014210101','21005',55.0),('2014210101','21006',80.0),('2014210101','31001',68.0),('2014210101','31002',77.0),('2014210101','31005',85.0),('2014210102','21002',95.0),('2014210102','21004',88.0),('2014310101','21001',79.0),('2014310101','21004',80.0),('2014310102','21001',91.0),('2014310102','21004',87.0);
/*!40000 ALTER TABLE `tb_score` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tb_student`
--

DROP TABLE IF EXISTS `tb_student`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_student` (
  `studentNo` char(10) NOT NULL,
  `studentName` varchar(10) NOT NULL,
  `sex` char(2) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `native` varchar(20) DEFAULT NULL,
  `nation` varchar(20) DEFAULT '汉',
  `classNo` char(6) DEFAULT NULL,
  PRIMARY KEY (`studentNo`),
  KEY `fk_student` (`classNo`),
  CONSTRAINT `fk_student` FOREIGN KEY (`classNo`) REFERENCES `tb_class` (`classNo`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tb_student`
--

LOCK TABLES `tb_student` WRITE;
/*!40000 ALTER TABLE `tb_student` DISABLE KEYS */;
INSERT INTO `tb_student` VALUES ('2013110101','张晓勇','男','1997-12-11','山西','汉','AC1301'),('2013110103','王一敏','女','1996-03-25','河北','汉','AC1301'),('2013110201','江山','女','1996-09-17','内蒙','锡伯','AC1302'),('2013110202','李明','男','1996-01-14','广西','壮','AC1302'),('2013310101','黄菊','女','1995-09-30','北京','汉','IS1301'),('2013310102','林海','男','1996-01-18','北京','满','IS1301'),('2013310103','吴昊','男','1995-11-18','河北','汉','IS1301'),('2014210101','黄涛','男','1997-04-03','湖南','侗','CS1401'),('2014210102','郭志坚','男','1997-02-21','上海','汉','CS1401'),('2014210103','王玲','女','1998-02-21','安徽','汉','CS1401'),('2014310101','王林','男','1996-10-09','河南','汉','IS1401'),('2014310102','李怡然','女','1996-12-31','辽宁','汉','IS1401'),('2015310103','李彤','男',NULL,NULL,'傣','IS1401');
/*!40000 ALTER TABLE `tb_student` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2018-11-15 23:42:32

2.字符集设置

2.1 在MySQL中创建一个名为db_school的数据库,要求设置默认字符集为GB2312,
字符集的校对规则为gb2312_chinese_ci。
在这里插入图片描述

show collation
show collation where `Charset`='GB2312' and  `Collation` like '%ci';

CREATE DATABASE db_school CHARACTER SET GB2312 COLLATE gb2312_chinese_ci;

show databases;

--查看当前数据库字符集
show VARIABLES like 'character%';  

--设置数据库字符集
alter database db_school character set GBK;  

2.2 查看当前用户可查看的数据库列表
在这里插入图片描述
3. 修改已有数据库db_school的默认字符集和校对规则分别为GBK, GBK_chinese_ci
在这里插入图片描述在这里插入图片描述

--同时设置字符集合校对规则
alter database db_school DEFAULT CHARACTER SET GBK COLLATE gbk_chinese_ci;
show collation where `Charset`='GBK' and  `Collation` like '%ci';

3.表的创建、修改、删除

在这里插入图片描述

##创建表
create table if not exists tb_student (
studentNo CHAR(10) not NULL primary key comment '学号',
studentName VARCHAR(10) NOT null comment '姓名',
sex CHAR(2) comment '性别',
birthday date comment '出生日期',
native VARCHAR(20) comment '籍贯',
nation VARCHAR(10) DEFAULT '汉' comment '民族',
classNo CHAR(6) comment '所属班级'
) ENGINE=InnoDB comment '学生表';

desc tb_student;
show columns from tb_student;

3.1 用命令show tables查看当前数据库中的所有表
在这里插入图片描述

3.2 .将tb_student的表结构复制到tb_student2,并向tb_student2中添加一个INT型字段id,
要求其不能为NULL,取值唯一且自动增加,并将该字段添加到表的第一个字段

create table tb_student2 select * from tb_student where 1=3;

alter table tb_student2 add id int
Alter table tb_student2 add primary key(id); -先创建主键
ALTER TABLE tb_student2 MODIFY id int not null AUTO_INCREMENT;  --自增

3.3 .向tb_student表中添加一个varchar(16)类型的字段department,用于描述学生所在院系,要求设置其默认值为“城市学院”,并将该字段添加到原表nation之后

alter table tb_student add department varchar(16) 
DEFAULT '城市学院' comment '院系' after nation;

3.4.将tb_student中的字段birthday重命名为age,并将其数据类型更改为TINYINT,
允许其为NULL,默认值为18。

用DESC 查看tb_student
alter table tb_student change birthday age TINYINT DEFAULT 18;  --给字段重命名

3.5.将tb_student表中的字段department的默认值删除

ALTER TABLE tb_student ALTER COLUMN department DROP DEFAULT;

3.6.将tb_student表中的字段department的默认值改为’环化学院’

ALTER TABLE tb_student ALTER COLUMN department SET DEFAULT '环化学院';

3.7.将tb_student表中的字段department的数据类型更改为varchar(20),
取值不允许为空,并将此字段移至字段studentName之后。

用desc tb_student命令查看结果
ALTER TABLE tb_student MODIFY department varchar(20) not null after studentName;

3.8 .删除数据表tb_student2中的字段id

ALTER TABLE tb_student2 MODIFY id int not null;  //删除自增长
Alter table tb_student2 drop primary key;//删除主建

ALTER TABLE tb_student2 DROP id;

3.9.使用RENAME [TO]子句将数据库db_school中的数据表tb_student2
重新命名为backup_tb_student

alter table tb_student2 rename to backup_tb_student;

3.10.使用RENAME TABLE语句将数据库db_school中的表
backup_tb_student再重新命名为tb_student2

RENAME TABLE backup_tb_student TO tb_student2,new_table TO old_table;
drop table tb_student,tb_student2;

4.数据完整性约束

4.1 重新按照表1创建tb_student数据表,要求以表级完整性约束方式定义主键,
并指定主键约束名为pk_student。

CREATE TABLE tb_student (
 studentNo CHAR(10) NOT NULL,
 studentName VARCHAR(10) NOT NULL,
 sex CHAR(2),
 birthday DATE, 
 native VARCHAR(20),
 nation VARCHAR(20) default '汉',
 classNo CHAR(6),
 constraint pk_student primary key(studentNo)
) engine=InnoDB default charset=gb2312;

4.2 在数据库db_school中,按照表2的结构创建tb_class。要求:使用InnoDB存储引擎,gb2312字符集,主键约束为列级完整性约束,唯一约束为表级完整性约束其约束名为uq_class
在这里插入图片描述

CREATE TABLE tb_class (
 classNo CHAR(6) PRIMARY KEY NOT NULL,
 className VARCHAR(20) NOT NULL,
 department VARCHAR(20),
 grade ENUM('1','2','3','4'), 
 classNum TINYINT,
 constraint uq_class unique(className)
) engine=InnoDB default charset=gb2312;

4.3 首先删除数据表tb_student,按照表1重新创建tb_student,在创建的同时建立tb_student到tb_class的外键约束(两个表相同含义的属性是classNo,因此classNo是tb_student的外键),约束名为fk_student,并定义相应的参照动作,更新操作为级联(cascade),删除操作为限制(restrict),数据表引擎为InnoDB,字符集为gb2312

drop table tb_student;

CREATE TABLE tb_student (
 studentNo CHAR(10) NOT NULL,
 studentName VARCHAR(10) NOT NULL,
 sex CHAR(2),
 birthday DATE, 
 native VARCHAR(20),
 nation VARCHAR(20) default '汉',
 classNo CHAR(6),
 constraint fk_student FOREIGN KEY (classNo)
 references tb_class(classNo) on delete restrict on update cascade
) engine=InnoDB default charset=gb2312;

4.4 在数据库db_school中按照表3创建tb_course表,
要求:外键名字为fk_course,引擎为InnoDB,默认字符集为gb2312。
在这里插入图片描述

CREATE TABLE tb_course (
 courseNo CHAR(6) NOT NULL primary key comment '课程号',
 courseName VARCHAR(20) unique not NULL comment '课程名',
 credit DECIMAL(3,1) not NULL comment '学分',
 courseHour TINYINT(2) not NULL comment '课时数', 
 term TINYINT(2) comment '开课学期',
 priorCourse CHAR(6) comment '先修课程',
 constraint fk_course FOREIGN KEY(priorCourse) REFERENCES tb_course(courseNo)
) engine=InnoDB default charset=gb2312;

4.5 在数据库db_school中定义数据表tb_score,
表结构如表4所示, 引擎为InnoDB,默认字符集为gb2312。
在这里插入图片描述

CREATE TABLE tb_score(
CREATE TABLE tb_score(
 studentNo CHAR(10) NOT NULL comment '学号',
 courseNo CHAR(6) NOT NULL comment '课程号',
 credit DECIMAL(4,1) not NULL comment '成绩',
 constraint fk_score_stuNo FOREIGN KEY(studentNo) REFERENCES tb_student(studentNo),  
 constraint fk_score_courNo FOREIGN KEY(courseNo) REFERENCES tb_course(courseNo),
 constraint pk_score PRIMARY KEY(studentNo,courseNo)
) engine=InnoDB default charset=gb2312;

注:外键约束对应的主键(在表里是主键才可以)

5.更新完整性约束条件

5.1 删除在表tb_score中定义的外键约束fk_score_stuNo

alter table tb_score drop foreign key fk_score_stuNo;

5.2 .删除在表tb_student中定义的主键约束。

Alter table tb_student drop primary key;

5.3 添加主键约束,用alter table语句在tb_student对studentNo重新添加主键。

Alter table tb_student add primary key(studentNo); 

5.4.添加外键约束,用alter table语句在tb_score表对studentNo重新添加外键,
对应的主键为tb_student表的studentNo,外键名称为fk_score_stuNo。

ALTER TABLE tb_score ADD CONSTRAINT 
fk_score_stuNo FOREIGN KEY(studentNo) REFERENCES tb_student(studentNo); 

6.索引的创建

6.1.创建新表的同时创建普通索引:要求按照实验一第5题表1的结构创建tb_student1表,
要求在创建的同时在studentName字段上建立普通索引,索引名为idx_studentName。

create table if not exists tb_student1 (
studentNo CHAR(10) not NULL primary key comment '学号',
studentName VARCHAR(10) NOT null comment '姓名',
sex CHAR(2) comment '性别',
birthday date comment '出生日期',
native VARCHAR(20) comment '籍贯',
nation VARCHAR(10) DEFAULT '汉' comment '民族',
classNo CHAR(6) comment '所属班级',
INDEX idx_studentName(studentName)
) ENGINE=InnoDB comment '学生表';

6.2.创建新表时创建唯一索引:按照实验一第20题表2的结构创建tb_class1表,
要求在创建的同时在className字段上建立唯一索引,索引名为uqidx_className。

CREATE TABLE tb_class1 (
 classNo CHAR(6) PRIMARY KEY NOT NULL,
 className VARCHAR(20) NOT NULL,
 department VARCHAR(20),
 grade ENUM('1','2','3','4'), 
 classNum TINYINT,
 constraint uq_class unique(className),
 UNIQUE INDEX uqidx_className(className)
) engine=InnoDB default charset=gb2312;

6.3.在创建新表的同时创建主键索引:
按照第4部分表3的结构创建tb_course1,
要求创建的同时在courseNo字段上建立主键索引。

CREATE TABLE tb_course1 (
 courseNo CHAR(6) primary key comment '课程号',
 courseName VARCHAR(20) unique not NULL comment '课程名',
 credit DECIMAL(3,1) not NULL comment '学分',
 courseHour TINYINT(2) not NULL comment '课时数', 
 term TINYINT(2) comment '开课学期',
 priorCourse CHAR(6) comment '先修课程'
) engine=InnoDB default charset=gb2312;

6.4.使用create index语句创建索引:
按照第4部分表4的结构创建tb_score1,
要求使用create index 语句对studentNo建立普通降序索引,索引名为idx_studentNo,
对courseNo建立普通升序索引,索引名为idx_courseNo.

CREATE TABLE tb_score1(
 studentNo CHAR(10) NOT NULL comment '学号',
 courseNo CHAR(6) NOT NULL comment '课程号',
 credit DECIMAL(4,1) not NULL comment '成绩'
) engine=InnoDB default charset=gb2312;

alter table tb_score1 add index idx_studentNo(studentNo desc);
alter table tb_score1 add index idx_courseNo(courseNo);

6.5.使用create index语句创建基于字段值前缀字符的索引:
在tb_course上建立一个索引,要求按课程名称courseName字段值的前三个字符建立降序索引。

--函数要再加个括号
alter table tb_course add index idx_courseName1((left(courseName,3)) desc);  
DROP INDEX idx_courseName1 on tb_course;

6.6.使用alter table语句建立普通索引:在tb_score上建立普通索引,
要求使用alter table语句对courseNo字段建立普通索引,索引名为idx_courseNo.

alter table tb_score add index idx_courseNo(courseNo);

7.插入、更新、删除

7.1 按照图1的内容向tb_class表中插入记录

在这里插入图片描述

INSERT INTO tb_class(classNo,department,className) VALUES('AC1301', '会计学院', '会计 13-1 班');
INSERT INTO tb_class(classNo,department,className) VALUES('AC1302', '会计学院', '会计 13-2 班');
INSERT INTO tb_class(classNo,department,className) VALUES('CS1401', '计算机学院', '计算机 14-1 班');
INSERT INTO tb_class(classNo,department,className) VALUES('IS1301', '信息学院', '信息系统 13-1 班');
INSERT INTO tb_class(classNo,department,className) VALUES('IS1401', '信息学院', '信息系统 14-1 班');

7.2 使用批量插入记录的方法,一次性向tb_student表中插入如图2所示的记录
加粗样式

INSERT INTO tb_student
values ('2013110101', '张晓勇', '男', '1977-12-11','山西','汉','AC1301'),
('2013110103', '王一敏', '女', '1996-03-25','河北','汉','AC1301'),
('2013110201', '江山', '女', '1996-09-17','内蒙','锡伯','AC1302'),
('2013110202', '李明', '男', '1996-01-14','广西','壮','AC1302'),
('2013310101', '黄菊', '女', '1995-09-30','北京','汉','IS1301'),
('2013310102', '林海', '男', '1996-01-18','北京','满','IS1301'),
('2013310103', '吴昊', '男', '1995-11-18','河北','汉','IS1301'),
('2014210101', '刘涛', '男', '1997-04-03','湖南','侗','CS1401'),
('2014210102', '郭志坚', '男', '1997-04-03','上海','汉','CS1401'),
('2014210103', '王玲', '女', '1998-02-21','安徽','汉','CS1401'),
('2014310101', '王林', '男', '1996-10-09','河南','汉','IS1401'),
('2014310102', '李怡然', '女', '1996-12-31','辽宁','汉','IS1401');

7.3.向tb_student表中插入一条新的记录,
学号为’2015310103’,姓名为’李彤’,性别为’男’,民族为‘傣’,班级编号为’IS1401’
(注意,这是部分字段的值)。

INSERT INTO tb_student(studentNo,studentName,sex,nation,classNo) 
values('2015310103','李彤','男','傣','IS1401');

7.4.向tb_student1表中插入tb_student表中所有汉族学生的信息。

insert into tb_student1 select * from tb_student where nation='汉';

7.5.在tb_student表中,使用replace 语句把学号为“2014310102”的学生姓名替换为李怡。

select * from tb_student where studentNo='2014310102';
update tb_student set studentName=replace(studentName,'然','') where studentNo='2014310102';

7.6.使用update语句,把tb_student表中学号为’2014210101’的学生姓名更改为’黄涛’.

update tb_student set studentName='黄涛' where studentNo='2014210101';

7.7.删除tb_student表中姓名为“王一敏“的学生信息。

delete from tb_student where studentName='王一敏';

8.数据查询

重新导入建表语句
mysql> source d:/create_db.sql

第一部分 select语句基本用法
1.查询所有班级的班级编号、所属学院和班级名称
select classNo,department,className from tb_class;

2.从tb_class表中查询所有的学院名称。
select distinct department from tb_class;

3.查询全体学生的详细信息
select * from tb_student;

4.查询全体学生的姓名、性别和年龄
select studentName,sex,year(now())-year(birthday) age 
from  tb_student;

5.查询全体学生的姓名、性别和年龄,要求用汉语显示目标列表的名称。
select studentName as '姓名',
sex as '性别',
year(now())-year(birthday) as '年龄'
from  tb_student;

6.查询课时大于等于48学时的课程名称和学分
select courseName,credit from tb_course 
where courseHour >= 48;

7.查询少数民族学生的姓名、性别、籍贯和民族
select studentName,sex,nation, native 
from tb_student where  nation <> '汉';

8.查询1997年出生的学生姓名、性别和具体日期。
select studentName,sex,birthday 
from tb_student 
where year(birthday)=1997;

9.查询不是1997年出生的学生姓名、性别和具体日期。
select studentName,sex,birthday 
from tb_student where year(birthday)!=1997;

10.查询籍贯是北京、天津和上海的学生信息。
select * from tb_student 
where native in ('北京','天津','上海');

11.查询籍贯不是北京、天津和上海的学生信息。
select * from tb_student 
where native not in ('北京','天津','上海');

12.查询2013年入学的学生全部信息。
select * from tb_student 
where left(studentNo,4)='2013';

13.查询所有姓王的学生的学号、姓名和班级编号。
select studentNo,studentName,classNo 
from tb_student where studentName like '王%';

14.查询所有不姓王的学生的学号、姓名和班级编号。
select studentNo,studentName,classNo from tb_student 
where studentName not like '王%';

15.	查询姓名中包含‘林’字的学生的学号、姓名和班级编号。
select studentNo,studentName,classNo 
from tb_student where studentName like '%林%';

16.查询姓王的且姓名为三个字的学生的学号、姓名和班级编号。
select studentNo,studentName,classNo from tb_student 
where studentName like '王%' and CHAR_LENGTH(studentName)=3;

17.查询课程名称中包含’-‘符号的课程信息;
select * from tb_course where courseName like '%-%';

18.查询课程名称中带有中文‘系统’的课程信息。
select * from tb_course where courseName like '%系统%';

19.查询课程名称中含有‘管理’、‘信息’或者‘系统’的课程信息。
select * from tb_course 
where courseName like '%管理%' or courseName like '%信息%' or courseName like '%系统%';

20.查询缺少先修课的课程信息。
select * from tb_course where priorCourse is null;

21.查询所有有先修课的课程信息
select * from tb_course where priorCourse is not null;

22.查询学分大于等于3且学时数大于32的的课程名称、学分和学时数。
select courseName,credit,courseHour 
from tb_course 
where credit=3 and courseHour>32;

23.查询籍贯是北京或者上海的学生的姓名、籍贯和民族。
select  studentName,native, nation 
from tb_student 
where native in ('北京','上海');

24.查询籍贯是北京或湖南的少数民族男生的姓名、籍贯和民族。
select  studentName,native, nation 
from tb_student where native in ('北京','湖南') 
and nation<>'汉';

25.查询学生的姓名、籍贯和民族,并将查询结果按姓名升序排序。
select * from tb_student order by studentName;

26.查询学生选课成绩大于85分的学号、课程号和成绩信息,并将查询结果先按学号升序排列,再按成绩降序排列。
select * from tb_score 
where  score>85 
order by studentNo,score desc;

27.查询成绩排名第3至第5的学生学号、课程号和成绩
select * from tb_score 
order by score desc limit 2,3;

第二部分 使用聚合函数查询
28.查询学生总人数。
select count(*) from tb_student;

29.查询选修了课程的学生总人数。
select sum(classNum) from tb_class;

30.计算选修课程编号为‘21001’的学生平均成绩。
select avg(score) from tb_score where courseNo='21001';

31.计算选修课程编号为‘21001’的学生最高分。
select max(score) from tb_score where courseNo='21001';

第三部分 分组聚合查询
32.查询各个课程号以及相应的选课人数。
select courseNo,count(*) from tb_score group by courseNo;

33.查询每个学生的选课门数、平均分和最高分
select studentNo,count(courseNo),avg(score),max(score) 
from tb_score group by studentNo;

34.查询平均分在80分以上的每个同学的选课门数、平均分和最高分。
select studentNo,count(courseNo),avg(score),max(score) 
from tb_score group by studentNo having avg(score)>80;

35.查询有2门以上(含2门)课程的成绩大于88分的学生学号及(88分以上的)课程数。
select studentNo,count(courseNo) 
from tb_score where score> 88 group by studentNo 
having count(courseNo)>=2;

36.查询所有学生选课的平均成绩,但只有当平均成绩大于80的情况下才输出。
select studentNo,avg(score) 
from tb_score group by studentNo having avg(score)>80;

第四部分 多表连接查询
37.查询每个学生选修课程的情况
select b.studentNo,b.studentName,c.* 
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo;

38.查询会计学院全体同学的学号、姓名、籍贯、班级编号和所在班级名称。
select a.studentNo,a.studentName,a.native,a.classNo,b.className
from tb_student a,tb_class b
where a.classNo = b.classNo
and b.department ='会计学院';

39.	查询选修了课程名称为‘程序设计’的学生学号、姓名和成绩。
select b.studentNo,b.studentName,a.score 
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='程序设计';

40.查询与数据库这门课学分相同的课程信息。
select * from tb_course a where a.credit in 
(select credit from tb_course b 
where a.credit=b.credit and b.courseName = '数据库')
and a.courseName <> '数据库';

41.使用左连接查询所有学生及其选修课程的情况,
包括没有选修课程的学生,要求显示学号、姓名、性别、班号、选修的课程号和成绩。

select a.studentNo,a.studentName,a.sex,a.classNo,c.courseName,b.score 
from tb_student a left join tb_score b on a.studentNo = b.studentNo
join tb_course c on b.courseNo=c.courseNo;


42.使用右连接查询所有学生及其选修课程的情况,
包括没有选修课程的学生,要求显示学号、姓名、性别、班号、选修的课程号和成绩。

select a.studentNo,a.studentName,a.sex,a.classNo,c.courseName,b.score 
from tb_student a right join tb_score b on a.studentNo = b.studentNo
join tb_course c on b.courseNo=c.courseNo;

第五部分 子查询
43.查询选修了课程的学生姓名
select a.studentName from tb_student a where a.studentNo in
(select b.studentNo from tb_score b);

44.	查询没有选修过课程的学生姓名。
select a.studentName from tb_student a where a.studentNo not in
(select b.studentNo from tb_score b);

45.查询班级‘计算机14-1班’所有学生的学号和姓名。
select a.studentNo,a.studentName from tb_student a where a.classNo in 
(select b.classNo from tb_class b where b.className ='计算机14-1班');

46.查询与‘李明’同班的学生学号、姓名和班级编号。
select * from tb_student a
where a.classNo in 
(select b.classNo from tb_student b where b.studentName='李明')
and a.studentName != '李明';

47.查询男生中比任意一个女生出生年份都晚的学生姓名和出生年份。
select * from tb_student a where a.birthday > any
(select birthday from tb_student b where b.sex ='女')
and a.sex ='男';

48.查询选修了课程号为‘31002’的学生姓名。
select a.studentName from tb_student a
where a.studentNo in 
(select b.studentNo from tb_score b where b.courseNo='31002');

49.查询没有选修课程号为‘31002’的学生姓名。
select a.studentName from tb_student a
where a.studentNo not in 
(select b.studentNo from tb_score b where b.courseNo='31002');

50.查询选修了全部课程的学生姓名
select a.studentName from tb_student a
where a.studentNo in (
select studentNo from tb_score group by studentNo
having count(*) = (select count(*) from tb_course)
);

第六部分 联合查询

51.使用UNION查询选修了‘管理学’或者‘计算机基础’的学生学号
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='管理学'
union
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='计算机基础';

52.使用UNION ALL查询选修了‘管理学’或者‘计算机基础’的学生学号。
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='管理学'
union all
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='计算机基础';

53.查询选修了‘计算机基础’,但没有选修‘管理学’的学生学号。
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName='计算机基础'
union
select b.studentNo
from tb_score a,tb_student b,tb_course c
where a.studentNo = b.studentNo
and a.courseNo = c.courseNo
and c.courseName<>'管理学';

9.自定义函数

第一部分 自定义函数创建、调用
1.编写函数名为fn_getMaleNum()的自定义函数,要求调用该函数后能显示男生的人数。
CREATE FUNCTION fn_getMaleNum() RETURNS int(10)
BEGIN
declare num int(10);
select count(*) from tb_student a
where a.sex ='男'
INTO num;
RETURN num;
END;

##调用函数
select fn_getMaleNum();

2.编写自定义函数fn_getClassNum(cNo char(6)),要求调用该函数后能根据班级编号显示该班级的人数。

CREATE FUNCTION fn_getClassNum(cNo char(6)) RETURNS int(10)
BEGIN
declare num int(10);
select ifnull(classNum,0) classNum from tb_class  where classNo = cNo
LIMIT 1
INTO num;
RETURN num;
END;

##调用函数
select fn_getClassNum('CS1401');


3.编写自定义函数fn_getCourseScore(sNo char(10),courNo char(6)),
要求调用该函数后能根据学号和课号显示该学生某门课的成绩

CREATE FUNCTION fn_getCourseScore(sNo char(10),courNo char(6)) RETURNS int(10)
BEGIN
declare num int(10);
select score from tb_score 
where studentNo = sNo
and courseNo = courNo
LIMIT 1
INTO num;
RETURN num;
END;

##调用函数
select fn_getCourseScore('2013110101','11003');

第二部分 自定义函数—条件控制语句
4.编写一个函数,要求根据调用时输入的性别显示相应的学生人数(从此题往后,函数名和参数名由同学自己拟定,注意函数名以fn_开头)

CREATE FUNCTION fn_getStuNum(Sex char(2)) RETURNS int(10)
BEGIN
declare num int(10);
select count(*) from tb_student a
where a.sex = Sex
INTO num;
RETURN num;
END;

##调用函数
select fn_getStuNum('男');
select fn_getStuNum('女');


5.编写一个函数,要求调用时输入学号,函数首先计算该学生所选课的平均成绩,
然后将成绩转换为5分制(转换方法: (成绩/100)*5,并保留整数部分),
结果如果是0、1或者2,输出‘不及格’,3,输出‘合格’,4,输出‘良好’,5,输出‘优秀’。

CREATE FUNCTION fn_getScore(sNo char(10)) RETURNS VARCHAR(10)
BEGIN
declare score int(10);
select CEILING((score/100)*5) from tb_score
where studentNo = sNo
LIMIT 1
INTO score;
if score=0 or score=1 or score=2  THEN
RETURN '不及格';
elseif score=3 THEN
RETURN '合格';
elseif score=4 THEN
RETURN '良好';
ELSE 
RETURN '优秀';
END IF;
END;

##调用函数
select fn_getScore('2013110101');

第三部分 自定义函数—循环语句
6.编写一个函数实现在某一个字符串后面循环拼接n个其它字符串,例如:
假设该函数名为fn_addStr(str1 varchar(20),str2 varchar(20),int),则调用后
Selecet fn_addStr(‘Hello’,’World’,4)
显示:HelloWorldWorldWorldWorld

create function fun_addStr(str1 varchar(100),str2 varchar(10),num int) returns varchar(200)
begin
declare i int default 1;
declare result varchar(200) default '';
set result=str1;
myloop:loop
set i=i+1;
set result=concat(result,str2);
if i>num
then
leave myloop;
end if;
end loop myloop; 
return result;
end;

##调用函数
select fun_addStr('Hello','World',8);

10.触发器函数

SET GLOBAL log_bin_trust_function_creators = 1;

use db_school;

DROP TRIGGER insert_score;


1.对tb_score表创建一个插入操作的触发器,当学生选完一门课向tb_score插入记录时,
先判断available是否不为零,如果不为0,
对应课程的available自动减一;如果为0,抛出一个错误表示该门课已不能选。
##cmd创口中执行

DELIMITER //
create trigger insert_score after insert on tb_score for each row
BEGIN
DECLARE num int; 
DECLARE msg VARCHAR (255); 
SET num = (select tb_course.available from tb_course where tb_course.courseNo = new.courseNo); 
 if num!=0 then
	update tb_course
	set available=up_limit- (select count(*) from tb_score where tb_score.courseNo=new.courseNo)
	where tb_course.courseNo= new.courseNo;
 else
	 signal sqlstate '45000' set message_text=msg;
 end if;
END;
//
DELIMITER ;

##答案
select f.TRIGGER_NAME,f.TRIGGER_NAME,
f.EVENT_MANIPULATION,f.ACTION_TIMING 
from information_schema.TRIGGERS f
where f.TRIGGER_SCHEMA ='db_school';
select * from tb_course a where a.courseNo ='21004';
select * from tb_score b
where b.studentNo ='2013110101';
INSERT into tb_score values('2013110101','21004',90);
select * from tb_course a where a.courseNo ='21004';

2.对tb_score表创建一个删除操作的触发器,
当有学生退选,从tb_score中删除选课记录时,
对应课程的available自动加1。

DELIMITER //
create trigger delete_score after delete on tb_score for each row
BEGIN 
	update tb_course  
	set available=available+1
	where tb_course.courseNo = OLD.courseNo;
END;
//
DELIMITER ;

##答案输出
select * from tb_course a where a.courseNo ='21004';
select * from tb_score b
where b.studentNo ='2013110101';
delete from tb_score b
where b.studentNo ='2013110101'
and b.courseNo='21004';
select * from tb_course a where a.courseNo ='21004';
select * from tb_score b
where b.studentNo ='2013110101';


3.编写一个存储过程,随机生成选课记录插入到tb_score表
注:mysql初始化不允许建存储过程
SET GLOBAL log_bin_trust_function_creators = 1;


DROP PROCEDURE insertcourse;
 
DELIMITER //
CREATE PROCEDURE pro_insert_course(IN sNo char(10))
BEGIN
declare studentno varchar(200);
select courseNo into studentno from tb_course f
where f.courseNo not in
(select d.courseNo from tb_score d
where d.studentNo =sNo)
ORDER BY RAND() LIMIT 0,1; 
IF studentno IS NOT NULL then
insert into tb_score VALUES (sNo,studentno,90);
END IF;
END;
//
DELIMITER ;

##答案输出
SELECT q.routine_name,q.routine_type,routine_schema
FROM information_schema.routines q
WHERE q.routine_schema ='db_school'
and q.routine_name ='pro_insert_course';
select * from tb_score b
where b.studentNo ='2013110103';
CALL pro_insert_course('2013110103');
select * from tb_score b
where b.studentNo ='2013110103';

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>