mysql语句查询

一、mysql语句查询

【包括:简单查询,条件查询,排序,聚合函数,分组函数】

先创建student和score表,添加基本数据,用于查询演练(参考答案如下)

创建student表SQL代码如下:

create table student(

      id int(10) not null unique primary key,

      name varchar(20) not null,

      gender varchar(4),

      birth year,

      department varchar(20),

      address varchar(50)

);

创建score表SQL代码如下:

create table score(

      id int(10) not null unique primary key auto_increment,

      stu_id int(10) not null,

      c_name varchar(20),

      grade int(10)

);

向student表插入记录的insert语句如下:

insert into student values

( 901,'张老大','男',1985,'计算机系','北京市海淀区'),

( 902,'张老二', '男',1986,'中文系', '北京市昌平区'),

( 903,'张三', '女',1990,'中文系', '湖南省永州市'),

( 904,'李四', '男',1990,'英语系', '辽宁省阜新市'),

( 905,'王五', '女',1991,'英语系', '福建省厦门市'),

( 906,'王六', '男',1988,'计算机系', '湖南省衡阳市');

向score表插入记录的insert语句如下:

insert into score values

(NULL,901, '计算机',98),

(NULL,901, '英语', 80),

(NULL,902, '计算机',65),

(NULL,902, '中文',88),

(NULL,903, '中文',95),

(NULL,904, '计算机',70),

(NULL,904, '英语',92),

(NULL,905, '英语',94),

(NULL,906, '计算机',90),

(NULL,906, '英语',85);

查询student表的所有记录

select * from student;

查询student表的第2条到第4条记录

select * from student limit 1,3;

从student表查询所有学生的学号(id)、姓名(name)和院系(department)的信息

select id,name,department from student;

从student表中查询计算机系和英语系的学生的信息

select * from student where department in ('计算机系','英语系');

从student表中查询年龄22~26岁的学生信息

select

  id,

  name,

  gender,

  date_format(now(),'%Y')-birth as age,

  department,

  address

from student

where year(now())-birth>=22 and year(now())-birth

二、接上表


从student表中查询每个院系有多少人

select department,count(id) from student group by department;

从score表中查询每个科目的最高分

select c_name,max(grade) from score group by c_name;

查询李四的考试科目(c_name)和考试成绩(grade)

select

  c_name,

  grade

from score

where stu_id = (select id from student where name='李四');

用连接的方式查询所有学生的信息和考试信息

select   *   from student as stu

inner join score

on stu.id = score.stu_id;

查询每个学生的总成绩

select  

   stu.id,

  stu.name,

  sum(grade)

from student as stu

inner join score

on stu.id = score.stu_id

group by stu.id,stu.name;

查询每个考试科目的平均成绩

select c_name,avg(grade) from score group by c_name;

查询计算机成绩低于95的学生信息

select

  *

from student

where id in (select stu_id from score where c_name='计算机' and grade<95)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。