Mysql学习

一、基础语法说明

1、)软件安装
2、)Mysql的特点:

特性:

   1、内部构件和可移植性
   
   2、使用C和C++编写 
   
  3、 用众多不同的编译器进行了测试 
   
   4、能够工作在众多不同的平台上。请参见2.1.1 “MySQL支持的操作系统”。
   
  5、 使用GNU Automake、Autoconf和Libtool进行移植。
   
   6、提供了用于C、C++、Eiffel、Java、Perl、PHP、Python、Ruby和Tcl的API。请参见第25章:API和库。
   
   7、采用核心线程的完全多线程 如果有多个CPU,它能方便地使用这些CPU。
   
   8、提供了事务性和非事务性存储引擎。
   
   9、使用了极快的“B树”磁盘表(MyISAM)和索引压缩。
   
   10、添加另一个存储引擎相对简单。如果打算为内部数据库添加一个SQL接口,该特性十分有用。
   
  11、 极快的基于线程的内存分配系统。
   
   12、通过使用优化的“单扫描多连接”,能实现极快的连接。
   
   13、存储器中的哈希表用作临时表。
   
   14、SQL函数是使用高度优化的类库实现的,运行很快。通常,在完成查询初始化后,不存在存储器分配。
   
   15、采用Purify(商业内存溢出检测器)以及GPL工具Valgrind(http://developer.kde.org/~sewardj/)测试了MySQL代码。
   
   16、服务器可作为单独程序运行在客户端/服务器联网环境下。它也可作为库提供,可嵌入(链接)到独立的应用程序中。这类应用程序可单独使用,也能在网络环境下使用。

列类型:

众多列类型: 带符号/无符号整数,1、2、3、4、8字节长,FLOAT,DOUBLE,CHAR,VARCHAR,TEXT,BLOB,DATE,TIME,DATETIME,TIMESTAMP,YEAR,SET,ENUM,以及OpenGIS空间类型。请参见第11章:列类型。 

语句和函数:

1、在SELECT和查询的WHERE子句中,提供完整的操作符和函数支持。例如:
mysql> SELECT CONCAT(first_name, ' ', last_name)
    -> FROM citizen
    -> WHERE income/dependents > 10000 AND age > 30;
    
2、对SQL GROUP BY和ORDER BY子句的全面支持。支持聚合函数(COUNT(), COUNT(DISTINCT ...),AVG(),STD(),SUM(),MAX(),MIN()和GROUP_CONCAT())。

3、支持LEFT OUTER JOIN和RIGHT OUTER JOIN,采用标准的SQL和ODBC语法。

4、按照标准SQL的要求,支持表别名和列别名。

5、DELETE、INSERT、REPLACE和UPDATE返回更改(影响)的行数。连接到服务器时,可通过设置标志返回匹配的行数。

6、MySQL的SHOW命令可用于检索关于数据库、数据库引擎、表和索引的信息。EXPLAIN命令可用于确定优化器处理查询的方式。

7、函数名与表名或列名不冲突。例如,ABS是有效的列名。唯一的限制在于,调用函数时,函数名和随后的符号“(”之间不得有空格。请参见9.6 “MySQL中保留字的处理”。 

8、可以将不同数据库的表混合在相同的查询中(就像MySQL 3.22中那样)。

安全

十分灵活和安全的权限和密码系统,允许基于主机的验证。连接到服务器时,所有的密码传输均采用加密形式,从而保证了密码安全

可伸缩性和限制

1、处理大型数据库: 我们使用了MySQL服务器和含5千万条记录的数据库。我们还听说,有些用户将MySQL用于含60000个表和约50亿行的数据库。 

2、每个表可支持高达64条索引(在MySQL 4.1.2之前为32条)。每条索引可由1~16个列或列元素组成。最大索引宽度为1000字节(在MySQL 4.1.2之前为500)。索引可使用具备CHAR、VARCHAR、BLOB或TEXT列类型的列前缀。

连接性

1、在任何平台上,客户端可使用TCP/IP协议连接到MySQL服务器。在Windows系统的NT系列中(NT、2000、XP或2003),客户端可使用命名管道进行连接。在Unix系统中,客户端可使用Unix域套接字文件建立连接。

2、在MySQL 4.1和更高的版本中,如果是以“--shared-memory”选项开始,Windows服务器还支持共享内存连接。客户端可使用“--protocol=memory”选项,通过共享内存建立连接。

3、Connector/ODBC (MyODBC)接口为使用ODBC(开放式数据库连接性)连接的客户端程序提供了MySQL支持。例如,可以使用MS Access连接到你的MySQL服务器。客户端可运行在Windows或Unix平台上。提供了MyODBC源。支持所有的ODBC 2.5函数,以及众多其他函数。请参见第26章:连接器。

4、Connector/J接口为使用JDBC连接的Java客户端程序提供了MySQL支持。客户端可运行在Windows或Unix平台上。提供了Connector/J源码。请参见第26章:连接器。

本地化

1、服务器可使用多种语言向客户端提供错误消息。请参见5.10.2节,“设置错误消息语言”。

2、对数种不同字符集的全面支持,包括latin1 (cp1252)、german、big5、ujis等。例如,在表名和列名中允许使用斯堪的纳维亚字符‘å’、‘ä’和‘ö’。从MySQL 4.1开始,提供了Unicode支持。 

3、所有数据均以所选的字符集保存。正常字符串列的比较不区分大小写。

4、分类是根据所选的字符集(默认情况下,使用瑞典校对)进行的。启动MySQL服务器时,可更改该项设置。要想查看高级分类的示例,请参见Czech分类代码。MySQL服务器支持众多不同的字符集,这类字符集可在编译时和运行时指定。

客户端和工具

1、MySQL服务器提供了对SQL语句的内部支持,可用于检查、优化和修复表。通过mysqlcheck客户端,可在命令行上使用这类语句。MySQL还包括myisamchk,这是一种很快的命令行实用工具,可用于在MyISAM表上执行这类操作。请参见第5章:数据库管理。 

2、对于所有MySQL程序,均能通过“-help”或“-?”选项调用,以获取联机帮助信息。

3、)数据库操作

CREATE DATABASE `sql50` DEFAULT CHARACTER set utf8;                #创建数据库语句  
DROP DATABASE if EXISTS `sql50`;                                   #删除‘sql50’库
SHOW databases;                      							   #列出已有数据库
USE sql50;                                         				   #进入sql50库(进行别的操作)

4、)数据库表操作
创建表: – create table 表名(列名1(字段) 字段类型[约束条件],列名2 字段类型,…);

----------建表学生表:

CREATE TABLE `Student`(
	`s_id` VARCHAR(20),
	`s_name` VARCHAR(20) NOT NULL DEFAULT '',
	`s_birth` VARCHAR(20) NOT NULL DEFAULT '',
	`s_sex` VARCHAR(10) NOT NULL DEFAULT '',
	PRIMARY KEY(`s_id`)
);

----------创建课程表:

CREATE TABLE `Course`(
	`c_id`  VARCHAR(20),
	`c_name` VARCHAR(20) NOT NULL DEFAULT '',
	`t_id` VARCHAR(20) NOT NULL,
	PRIMARY KEY(`c_id`)
);

----------创建教师表:

CREATE TABLE `Teacher`(
	`t_id` VARCHAR(20),
	`t_name` VARCHAR(20) NOT NULL DEFAULT '',
	PRIMARY KEY(`t_id`)
);

----------创建成绩表:

CREATE TABLE `Score`(
	`s_id` VARCHAR(20),
	`c_id`  VARCHAR(20),
	`s_score` INT(3),
	PRIMARY KEY(`s_id`,`c_id`)
);

show tables;														#查看当前数据库中有哪些表:   
desc Student;   													#查看Student表数据
show create table Student;      									#查看Student表的细节

向表里添加数据:
插入多条数据数据:insert into 表名(列名1,列名2,…) values (列值1,列值2,…),values (列值1,列值2,…),…

--插入学生表测试数据

insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
insert into Student values('02' , '钱电' , '1990-12-21' , '男');
insert into Student values('03' , '孙风' , '1990-05-20' , '男');
insert into Student values('04' , '李云' , '1990-08-06' , '男');
insert into Student values('05' , '周梅' , '1991-12-01' , '女');
insert into Student values('06' , '吴兰' , '1992-03-01' , '女');
insert into Student values('07' , '郑竹' , '1989-07-01' , '女');
insert into Student values('08' , '王菊' , '1990-01-20' , '女');

--课程表测试数据

insert into Course values('01' , '语文' , '02');
insert into Course values('02' , '数学' , '01');
insert into Course values('03' , '英语' , '03');

--教师表测试数据

insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');

--成绩表测试数据

insert into Score values('01' , '01' , 80);
insert into Score values('01' , '02' , 90);
insert into Score values('01' , '03' , 99);
insert into Score values('02' , '01' , 70);
insert into Score values('02' , '02' , 60);
insert into Score values('02' , '03' , 80);
insert into Score values('03' , '01' , 80);
insert into Score values('03' , '02' , 80);
insert into Score values('03' , '03' , 80);
insert into Score values('04' , '01' , 50);
insert into Score values('04' , '02' , 30);
insert into Score values('04' , '03' , 20);
insert into Score values('05' , '01' , 76);
insert into Score values('05' , '02' , 87);
insert into Score values('06' , '01' , 31);
insert into Score values('06' , '03' , 34);
insert into Score values('07' , '02' , 89);
insert into Score values('07' , '03' , 98);

5、)四种语言
(1)DDL 数据定义语言

修改表名: rename table 原来表名 to 新表名;
rename TABLE Student to s; 
修改表的字符集:例如将表字符集改为gbk ,则是 alter table 表名 character set gbk;
alter table Student character set gbk;
删除表:drop table 表;
drop table Student;
删除数据库名:drop database 数据库名;

修改字段(列)
添加字段:alter table 表名 add 字段名 字段类型;
修改字段名:alter table 表名 change 原始字段名 新的字段名 新数据类型;
修改字段的数据类型:alter table 表名 modify 字段名 字段类型;
删除字段: alter table 表名 drop 字段名:

(2)DML 数据操作语言

修改更新数据:update 表名 set 列名1=列值1,列名2=列值2,... where 条件;           用where条件对指定数据进行修改

修改数据库密码:
第一种方式:(1)use mysql;
          (2)update user set authentication_string=password('密码') where user='root' and Host='localhost';
第二种方式:mysqladmin -u root = 新密码;输入旧密码就可修改

删除记录:
第一种:delete from 表名 where 条件;               能找回数据
第二种:trumcate table 表名;                       创建一个新的表,但是表原来的数据删除了,不能找回数据

(3)DQL 数据查询语言

1、查询数据显示指定字段:select 字段名1,字段名2,... from 表名;    (select * from 表名; 则是显示全部字段)

2、条件查询:

    =(等于)
    !=(不等于)
    <>(不等于)
    <(小于)
    <=(小于等于)
    >(大于)
    >=(大于等于)between ... and     
    in(set)  (在set集合中) 
    is null (为空) 
    is not null (不为空) 
    and(与)
    or(或)
    not(非)
    
          eg:select * from 表名 where age in (18,17,19);

3、模糊查询:通过关键字查询,格式为 like+通配符

	通配符:-(任意一个字符)
		   %(任意0-n个字符)
	      eg: 查询名字中带‘李’的人   select * from 表名 like '%李%';

4、字段查询:

     1. )distinct去重 :select distinct 字段名 from 表;      #显示指定字段,去掉了重复字段数据
	 2. )对数值型字段进行运算后显示:
          eg:   select 字段1+字段2 as 新字段名 from 表;       #将两字段进行运算后,显示新的字段名(字段1,字段2必须是数值型,若为空则可设置默认值,IFNULL(字段1,数值))
          eg:    select IFNULL(字段1,0)+IFNULL(字段2,0) as 新字段名 from 表;  默认空字段设为0

5、排序:select * from 表名 ORDER BY 字段1 ASC,字段2 DESC,...

       先按字段1排序,若有字段相同数据,在按字段2进行排序,以此类推    ASC为升序,DESC为降序

6、聚合函数:对统计的结果进行计算统计  

       COUNT() : 统计指定列不为null的行数        		  eg: select count(字段1) from 表 [where 条件];
       MAX() : 列中最大值             				  eg: select max(字段1) from 表 [where 条件];
       MIN() : 列中最小值               				  eg: select min(字段1) from 表 [where 条件];
       SUM() : 列的数值和,若不是数值类型则为0     		  eg: select sum(字段1) from 表 [where 条件];
       AVG() : 列的平均数,若不是数值类型则为0      		  eg: select avg(字段1) from 表 [where 条件];

二、经典sql50题

此处转载自 :https://blog.csdn.net/fashion2014/article/details/78826299/,暂时未验证正确性!!!
1、)表与字段熟知:

表名 字段1 字段2 字段3 字段4
Student s_id s_name s_birth s_sex
Course c_id c_name t_id
Score s_id c_id s_score
Teacher t_id t_name
2、)表与表之间的联系:
 	Student________s_id__________Score
 	
    Course________t_id__________Teacher
    
    Course________c_id__________Score
-- 1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数	
**题目分析:**
查询结果:               学生信息和课程分数两部分;
涉及:                  Student和Scourse两张表;
所需技能:               子查询和jion
select * from Student right join (select t1.s_id ,sc1,sc2 from 
(select s_id ,s_score as sc1 from Score where c_id='01')as t1,
(select s_id,s_score as sc2 from Score where c_id='02')as t2
where t1.s_id =t2.s_id and t1.sc1>t2.sc2) as r on Student.s_id =r.s_id;	


select a.* ,b.s_score as 01_score,c.s_score as 02_score from 
student a 
	join score b on a.s_id=b.s_id and b.c_id='01'
	left join score c on a.s_id=c.s_id and c.c_id='02' or c.c_id = NULL where b.s_score>c.s_score
	
--也可以这样写
	select a.*,b.s_score as 01_score,c.s_score as 02_score from student 		  a,score b,score c 
			where a.s_id=b.s_id 
			and a.s_id=c.s_id 
			and b.c_id='01' 
			and c.c_id='02' 
			and b.s_score>c.s_score
-- 2、查询"01"课程比"02"课程成绩低的学生的信息及课程分数
	
select a.* ,b.s_score as 01_score,c.s_score as 02_score from 
	student a left join score b on a.s_id=b.s_id and b.c_id='01' or b.c_id=NULL 
	 join score c on a.s_id=c.s_id and c.c_id='02' where b.s_score=60;
	

-- 4、查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩
		-- (包括有成绩的和无成绩的)
		
select b.s_id,b.s_name,ROUND(AVG(a.s_score),2) as avg_score from 
	student b 
	left join score a on b.s_id = a.s_id
	GROUP BY b.s_id,b.s_name HAVING avg_score <60
	union
select a.s_id,a.s_name,0 as avg_score from 
	student a 
	where a.s_id not in (
				select distinct s_id from score);


-- 5、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
select a.s_id,a.s_name,count(b.c_id) as sum_course,sum(b.s_score) as sum_score from 
	student a 
	left join score b on a.s_id=b.s_id
	GROUP BY a.s_id,a.s_name;
			
			
-- 6、查询"李"姓老师的数量 
select count(t_id) from teacher where t_name like '李%';
	
-- 7、查询学过"张三"老师授课的同学的信息 
select a.* from 
	student a 
	join score b on a.s_id=b.s_id where b.c_id in(
		select c_id from course where t_id =(
			select t_id from teacher where t_name = '张三'));

-- 8、查询没学过"张三"老师授课的同学的信息 
select * from 
    student c 
    where c.s_id not in(
        select a.s_id from student a join score b on a.s_id=b.s_id where b.c_id in(
        select a.c_id from course a join teacher b on a.t_id = b.t_id where t_name ='张三'));
-- 9、查询学过编号为"01"并且也学过编号为"02"的课程的同学的信息

select a.* from 
	student a,score b,score c 
	where a.s_id = b.s_id  and a.s_id = c.s_id and b.c_id='01' and c.c_id='02';
	
-- 10、查询学过编号为"01"但是没有学过编号为"02"的课程的同学的信息
			
select a.* from 
	student a 
	where a.s_id in (select s_id from score where c_id='01' ) and a.s_id not in(select s_id from score where c_id='02')
			

-- 11、查询没有学全所有课程的同学的信息 
--@wendiepei的写法
select s.* from student s 
left join Score s1 on s1.s_id=s.s_id
group by s.s_id having count(s1.c_id)<(select count(*) from course)	
--@k1051785839的写法
select *
from student
where s_id not in(
select s_id from score t1  
group by s_id having count(*) =(select count(distinct c_id)  from course)) 
-- 12、查询至少有一门课与学号为"01"的同学所学相同的同学的信息 

select * from student where s_id in(
	select distinct a.s_id from score a where a.c_id in(select a.c_id from score a where a.s_id='01')
	);
			
-- 13、查询和"01"号的同学学习的课程完全相同的其他同学的信息 
--@ouyang_1993的写法
SELECT
 Student.*
FROM
 Student
WHERE
 s_id IN (SELECT s_id FROM Score GROUP BY s_id HAVING COUNT(s_id) = (
    #下面的语句是找到'01'同学学习的课程数
    SELECT COUNT(c_id) FROM Score WHERE s_id = '01'
   )
 )
AND s_id NOT IN (
 #下面的语句是找到学过‘01’同学没学过的课程,有哪些同学。并排除他们
 SELECT s_id FROM Score
 WHERE c_id IN(
   #下面的语句是找到‘01’同学没学过的课程
   SELECT DISTINCT c_id FROM Score
   WHERE c_id NOT IN (
     #下面的语句是找出‘01’同学学习的课程
     SELECT c_id FROM Score WHERE s_id = '01'
    )
  ) GROUP BY s_id
) #下面的条件是排除01同学
AND s_id NOT IN ('01')
--@k1051785839的写法
SELECT
 t3.*
FROM
 (
  SELECT
   s_id,
   group_concat(c_id ORDER BY c_id) group1
  FROM
   score
  WHERE
   s_id <> '01'
  GROUP BY
   s_id
 ) t1
INNER JOIN (
 SELECT
  group_concat(c_id ORDER BY c_id) group2
 FROM
  score
 WHERE
  s_id = '01'
 GROUP BY
  s_id
) t2 ON t1.group1 = t2.group2
INNER JOIN student t3 ON t1.s_id = t3.s_id

-- 14、查询没学过"张三"老师讲授的任一门课程的学生姓名 
select a.s_name from student a where a.s_id not in (
	select s_id from score where c_id = 
				(select c_id from course where t_id =(
					select t_id from teacher where t_name = '张三')));

-- 15、查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩 
select a.s_id,a.s_name,ROUND(AVG(b.s_score)) from 
	student a 
	left join score b on a.s_id = b.s_id
	where a.s_id in(
			select s_id from score where s_score<60 GROUP BY  s_id having count(1)>=2)
	GROUP BY a.s_id,a.s_name

-- 16、检索"01"课程分数小于60,按分数降序排列的学生信息
select a.*,b.c_id,b.s_score from 
	student a,score b 
	where a.s_id = b.s_id and b.c_id='01' and b.s_score<60 ORDER BY b.s_score DESC;
		
-- 17、按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩
select a.s_id,(select s_score from score where s_id=a.s_id and c_id='01') as 语文,
				(select s_score from score where s_id=a.s_id and c_id='02') as 数学,
				(select s_score from score where s_id=a.s_id and c_id='03') as 英语,
			round(avg(s_score),2) as 平均分 from score a  GROUP BY a.s_id ORDER BY 平均分 DESC;
--@喝完这杯还有一箱的写法
SELECT a.s_id,MAX(CASE a.c_id WHEN '01' THEN a.s_score END ) 语文, 
MAX(CASE a.c_id WHEN '02' THEN a.s_score END ) 数学, 
MAX(CASE a.c_id WHEN '03' THEN a.s_score END ) 英语, 
avg(a.s_score),b.s_name FROM Score a JOIN Student b ON a.s_id=b.s_id GROUP BY a.s_id ORDER BY 5 DESC		
-- 18.查询各科成绩最高分、最低分和平均分:以如下形式显示:课程ID,课程name,最高分,最低分,平均分,及格率,中等率,优良率,优秀率
--及格为>=60,中等为:70-80,优良为:80-90,优秀为:>=90
select a.c_id,b.c_name,MAX(s_score),MIN(s_score),ROUND(AVG(s_score),2),
	ROUND(100*(SUM(case when a.s_score>=60 then 1 else 0 end)/SUM(case when a.s_score then 1 else 0 end)),2) as 及格率,
	ROUND(100*(SUM(case when a.s_score>=70 and a.s_score<=80 then 1 else 0 end)/SUM(case when a.s_score then 1 else 0 end)),2) as 中等率,
	ROUND(100*(SUM(case when a.s_score>=80 and a.s_score<=90 then 1 else 0 end)/SUM(case when a.s_score then 1 else 0 end)),2) as 优良率,
	ROUND(100*(SUM(case when a.s_score>=90 then 1 else 0 end)/SUM(case when a.s_score then 1 else 0 end)),2) as 优秀率
	from score a left join course b on a.c_id = b.c_id GROUP BY a.c_id,b.c_name
	
-- 19、按各科成绩进行排序,并显示排名
-- mysql没有rank函数
	select a.s_id,a.c_id,
        @i:=@i +1 as i保留排名,
        @k:=(case when @score=a.s_score then @k else @i end) as rank不保留排名,
        @score:=a.s_score as score
    from (
        select s_id,c_id,s_score from score GROUP BY s_id,c_id,s_score ORDER BY s_score DESC
)a,(select @k:=0,@i:=0,@score:=0)s
--@k1051785839的写法
(select * from (select 
t1.c_id,
t1.s_score,
(select count(distinct t2.s_score) from score t2 where t2.s_score>=t1.s_score and t2.c_id='01') rank
FROM score t1 where t1.c_id='01'
order by t1.s_score desc) t1)
union
(select * from (select 
t1.c_id,
t1.s_score,
(select count(distinct t2.s_score) from score t2 where t2.s_score>=t1.s_score and t2.c_id='02') rank
FROM score t1 where t1.c_id='02'
order by t1.s_score desc) t2)
union
(select * from (select 
t1.c_id,
t1.s_score,
(select count(distinct t2.s_score) from score t2 where t2.s_score>=t1.s_score and t2.c_id='03') rank
FROM score t1 where t1.c_id='03'
order by t1.s_score desc) t3)
-- 20、查询学生的总成绩并进行排名
select a.s_id,
	@i:=@i+1 as i,
	@k:=(case when @score=a.sum_score then @k else @i end) as rank,
	@score:=a.sum_score as score
from (select s_id,SUM(s_score) as sum_score from score GROUP BY s_id ORDER BY sum_score DESC)a,
	(select @k:=0,@i:=0,@score:=0)s
	
-- 21、查询不同老师所教不同课程平均分从高到低显示 
		
	select a.t_id,c.t_name,a.c_id,ROUND(avg(s_score),2) as avg_score from course a
		left join score b on a.c_id=b.c_id 
		left join teacher c on a.t_id=c.t_id
		GROUP BY a.c_id,a.t_id,c.t_name ORDER BY avg_score DESC;
-- 22、查询所有课程的成绩第2名到第3名的学生信息及该课程成绩
			
			select d.*,c.排名,c.s_score,c.c_id from (
                select a.s_id,a.s_score,a.c_id,@i:=@i+1 as 排名 from score a,(select @i:=0)s where a.c_id='01'  
								ORDER BY a.s_score DESC  
            )c
            left join student d on c.s_id=d.s_id
            where 排名 BETWEEN 2 AND 3
            UNION
            select d.*,c.排名,c.s_score,c.c_id from (
                select a.s_id,a.s_score,a.c_id,@j:=@j+1 as 排名 from score a,(select @j:=0)s where a.c_id='02'  
								ORDER BY a.s_score DESC
            )c
            left join student d on c.s_id=d.s_id
            where 排名 BETWEEN 2 AND 3
            UNION
            select d.*,c.排名,c.s_score,c.c_id from (
                select a.s_id,a.s_score,a.c_id,@k:=@k+1 as 排名 from score a,(select @k:=0)s where a.c_id='03' 
								ORDER BY a.s_score DESC
            )c
            left join student d on c.s_id=d.s_id
            where 排名 BETWEEN 2 AND 3;
			
-- 23、统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比


		select distinct f.c_name,a.c_id,b.`85-100`,b.百分比,c.`70-85`,c.百分比,d.`60-70`,d.百分比,e.`0-60`,e.百分比 from score a
				left join (select c_id,SUM(case when s_score >85 and s_score <=100 then 1 else 0 end) as `85-100`,
											ROUND(100*(SUM(case when s_score >85 and s_score <=100 then 1 else 0 end)/count(*)),2) as 百分比
								from score GROUP BY c_id)b on a.c_id=b.c_id
				left join (select c_id,SUM(case when s_score >70 and s_score <=85 then 1 else 0 end) as `70-85`,
											ROUND(100*(SUM(case when s_score >70 and s_score <=85 then 1 else 0 end)/count(*)),2) as 百分比
								from score GROUP BY c_id)c on a.c_id=c.c_id
				left join (select c_id,SUM(case when s_score >60 and s_score <=70 then 1 else 0 end) as `60-70`,
											ROUND(100*(SUM(case when s_score >60 and s_score <=70 then 1 else 0 end)/count(*)),2) as 百分比
								from score GROUP BY c_id)d on a.c_id=d.c_id
				left join (select c_id,SUM(case when s_score >=0 and s_score <=60 then 1 else 0 end) as `0-60`,
											ROUND(100*(SUM(case when s_score >=0 and s_score <=60 then 1 else 0 end)/count(*)),2) as 百分比
								from score GROUP BY c_id)e on a.c_id=e.c_id
				left join course f on a.c_id = f.c_id
				 
-- 24、查询学生平均成绩及其名次 

		select a.s_id,
				@i:=@i+1 as '不保留空缺排名',
				@k:=(case when @avg_score=a.avg_s then @k else @i end) as '保留空缺排名',
				@avg_score:=avg_s as '平均分'
		from (select s_id,ROUND(AVG(s_score),2) as avg_s from score GROUP BY s_id ORDER BY avg_s DESC)a,(select @avg_score:=0,@i:=0,@k:=0)b;
-- 25、查询各科成绩前三名的记录
			-- 1.选出b表比a表成绩大的所有组
			-- 2.选出比当前id成绩大的 小于三个的
		select a.s_id,a.c_id,a.s_score from score a 
			left join score b on a.c_id = b.c_id and a.s_score=85
	
-- 34、查询课程名称为"数学",且分数低于60的学生姓名和分数 
	
		select a.s_name,b.s_score from score b join student a on a.s_id=b.s_id where b.c_id=(
					select c_id from course where c_name ='数学') and b.s_score<60

-- 35、查询所有学生的课程及分数情况; 
	
		
		select a.s_id,a.s_name,
					SUM(case c.c_name when '语文' then b.s_score else 0 end) as '语文',
					SUM(case c.c_name when '数学' then b.s_score else 0 end) as '数学',
					SUM(case c.c_name when '英语' then b.s_score else 0 end) as '英语',
					SUM(b.s_score) as  '总分'
		from student a left join score b on a.s_id = b.s_id 
		left join course c on b.c_id = c.c_id 
		GROUP BY a.s_id,a.s_name


 -- 36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数; 
			select a.s_name,b.c_name,c.s_score from course b left join score c on b.c_id = c.c_id
				left join student a on a.s_id=c.s_id where c.s_score>=70

		

-- 37、查询不及格的课程
		select a.s_id,a.c_id,b.c_name,a.s_score from score a left join course b on a.c_id = b.c_id
			where a.s_score<60 
		
--38、查询课程编号为01且课程成绩在80分以上的学生的学号和姓名; 
		select a.s_id,b.s_name from score a LEFT JOIN student b on a.s_id = b.s_id
			where a.c_id = '01'	and a.s_score>80

-- 39、求每门课程的学生人数 
		select count(*) from score GROUP BY c_id;

-- 40、查询选修"张三"老师所授课程的学生中,成绩最高的学生信息及其成绩

		
		-- 查询老师id	
		select c_id from course c,teacher d where c.t_id=d.t_id and d.t_name='张三'
		-- 查询最高分(可能有相同分数)
		select MAX(s_score) from score where c_id='02'
		-- 查询信息
		select a.*,b.s_score,b.c_id,c.c_name from student a
			LEFT JOIN score b on a.s_id = b.s_id
			LEFT JOIN course c on b.c_id=c.c_id
			where b.c_id =(select c_id from course c,teacher d where c.t_id=d.t_id and d.t_name='张三')
			and b.s_score in (select MAX(s_score) from score where c_id='02')


-- 41、查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩 
	select DISTINCT b.s_id,b.c_id,b.s_score from score a,score b where a.c_id != b.c_id and a.s_score = b.s_score
	

-- 42、查询每门功成绩最好的前两名 
		-- 牛逼的写法
	select a.s_id,a.c_id,a.s_score from score a
		where (select COUNT(1) from score b where b.c_id=a.c_id and b.s_score>=a.s_score)<=2 ORDER BY a.c_id


-- 43、统计每门课程的学生选修人数(超过5人的课程才统计)。要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列  
		select c_id,count(*) as total from score GROUP BY c_id HAVING total>5 ORDER BY total,c_id ASC
		
-- 44、检索至少选修两门课程的学生学号 
		select s_id,count(*) as sel from score GROUP BY s_id HAVING sel>=2

-- 45、查询选修了全部课程的学生信息 
		select * from student where s_id in(		
			select s_id from score GROUP BY s_id HAVING count(*)=(select count(*) from course))


--46、查询各学生的年龄
	-- 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

	select s_birth,(DATE_FORMAT(NOW(),'%Y')-DATE_FORMAT(s_birth,'%Y') - 
				(case when DATE_FORMAT(NOW(),'%m%d')>DATE_FORMAT(s_birth,'%m%d') then 0 else 1 end)) as age
		from student;


-- 47、查询本周过生日的学生
	select * from student where WEEK(DATE_FORMAT(NOW(),'%Y%m%d'))=WEEK(s_birth)
	select * from student where YEARWEEK(s_birth)=YEARWEEK(DATE_FORMAT(NOW(),'%Y%m%d'))
	
	select WEEK(DATE_FORMAT(NOW(),'%Y%m%d'))

-- 48、查询下周过生日的学生
	select * from student where WEEK(DATE_FORMAT(NOW(),'%Y%m%d'))+1 =WEEK(s_birth)

-- 49、查询本月过生日的学生

	select * from student where MONTH(DATE_FORMAT(NOW(),'%Y%m%d')) =MONTH(s_birth)
	
-- 50、查询下月过生日的学生
	select * from student where MONTH(DATE_FORMAT(NOW(),'%Y%m%d'))+1 =MONTH(s_birth)

三、优化整理

你可能感兴趣的:(基础环境)