4.16-mysql查询

语法:
select [distinct] *| 列名,列名 from 表名 [where条件]
单表查询
#查询所有学生信息
select * from student
#查询 学号和姓名 并给 列取别名
SELECT stuno 学号 ,stuname as 姓名 from student
SELECT * from result
#在成绩表中查询参加考试了的学生的学号

DISTINCT 去掉重复项

SELECT DISTINCT stuno from result where score is not null
#查询地址不为空的学生的姓名
#空有2种情况 null ‘’
SELECT stuname from student where address is not null and address !=’’
#查询地址为空的学生的姓名
SELECT stuname from student where address is null or address =’’

select * from student
#按照年龄 从大到小 显示学生的所有信息
#排序 默认是升序 asc
select * from student ORDER BY borndate asc
#按照年龄 从小到到 显示学生的所有信息
select * from student ORDER BY borndate desc
#分页显示 学生的信息 要求 每页显示2行信息

limit 参数1,参数2 参数1 代表数据起始行的索引(从0开始) 参数2代表每页显示的行数

#第一页
select * from student limit 0,2
#第二页
select * from student limit 2,2

select * from result
#分组
#在成绩表中求出每个学生考试的平均分

avg()

#分组 GROUP BY

GROUP BY不会单独使用 而是结合其他函数一起使用

#select * from result GROUP BY stuno

select stuno 学号, avg(score) 平均分
from result
GROUP BY stuno
#分组条件 where一般是作为查询的条件 跟在 from 后面
#分组的条件 使用having

#在成绩表中求出每个学生考试的平均分 只显示及格的信息
select stuno 学号, avg(score) 平均分
from result
GROUP BY stuno
HAVING avg(score)>=60

#查询可能出现的情况
select
FROM
where # 查询的条件
GROUP BY #对前面查询的数据作分组
HAVING #对分组后的数据做筛选
order by #排序(对查询最终版的数据作排序显示)
LIMIT 0,2 #对 排序好的数据分页显示

select stuno 学号, avg(score) 平均分
from result
GROUP BY stuno
HAVING avg(score)>=50
order by avg(score)
limit 0,2

猜你喜欢

转载自blog.csdn.net/weixin_44691723/article/details/89342859