mysql中的高级查询语句

此随笔用到的数据全是来自  关于mysql中表关系的一些理解(一对一,一对多,多对多)

提及的    学院表,学生表,学生详情表,选课表,课程表 

单标查询:(查看学生表的学生名单)

select stu_name from student;

指定条件查询:(查询学生表中学号大于3的学生姓名)

select stu_name from student where stu_id > 3 ;

模糊查询(查询学生表中以小为姓的学生的全部信息)

select * from student where stu_name like"小%";

select * from student where stu_name like "小_";# 两个下划线表示“小xx”

排序:(以学生年龄升序排列,默认就是升序,可不写asc)

select * from stu_datalis order by sda_age asc;

降序排

select * from stu_datalis order by sda_age desc;

限制显示数量:(限制只显示学生学号在前三的全部信息)

select * from student limit 3;

限制只显示学生学号在3到5之间的全部信息(第2个数据后面的3个数据) 

select * from student limit 2,3;

聚合函数:(学生详情表中年级最大的是)

select max(sda_age) from stu_datalis;

max()最大值

min()最小值

sum()求和

avg()平均数

round(avg())四舍五入

count()统计

分组查询(group by  ,一般情况跟聚合函数一同使用)

查看学生表中各个学院所有的学生总和

select sc_id 学院,count(sc_id) 学生个数 from student group by sc_id;

 

分组条件(having,必须是select后面出现的字段):

查看学院id在前二的学生人数总和:

select sc_id 学院,count(sc_id) 学生人数 from student group by sc_id having sc_id < 3;

子查询(嵌套查询)

查询学生详情表中,学号大于3的

select * from stu_datalis where sda_id in (
    select stu_id from student where stu_id > 3
    );

关联查询

  内查询

    无条件内查询

    有条件内查询

  外查询

    左外连接

    右外连接

左外连接:

select stu_id 学号,stu_name 姓名,col_name 学院 from student left join college on col_id = sc_id;

原文地址:https://www.cnblogs.com/pywjh/p/9427360.html