起别名as


给字段起别名

-- select name as 姓名,age as 年龄,hometown as 家乡 from students where name='王昭君'

-- select name 姓名,age 年龄,hometown 家乡 from students where name='王昭君'

给表起别名

-- select s.name,s.age from students as s


消除重复数据

-- select distinct age,class from students

--select distinct * from students


比较运算


-- 例1:查询小乔的年龄

-- select age from students where name='小乔'

-- 例2:查询20岁以下的学生

-- select * from students where age<20


-- 例3:查询家乡不在北京的学生

-- select * from students where hometown<>'北京'



逻辑运算


-- 例1:查询年龄小于20的女同学

-- select * from students where age<20 and sex='女'

-- 例2:查询女学生或'1班'的学生

-- select * from students where sex='女' or class='1班'

-- 例3:查询非天津的学生

-- select * from students where not hometown='天津'



模糊查询


-- 例1:查询姓孙的学生

-- select * from students where name like '孙%'

-- 例2:查询姓孙且名字是一个字的学生

-- select * from students where name like '孙_'


-- 例3:查询叫乔的学生

-- select * from students where name like '%乔'


-- 例4:查询姓名含白的学生

select * from students where name like '%白%'



范围查询


-- 例1:查询家乡是北京或上海或广东的学生

-- select * from students where hometown in ('北京','上海','广东')

-- select * from students where hometown not in ('北京','上海','广东')


-- 例2:查询年龄为18至20的学生  between 20 and 18 小值在前

-- select * from students where age between 18 and 20


判空


-- 例1:查询没有填写身份证的学生

-- select * from students where card is null

非空

-- select * from students where card is not null


判断身份证为空字符

-- select * from students where card=''


排序

-- 例1:查询所有学生信息,按年龄从小到大排序

-- select * from students order by age asc


降序

-- select * from students order by age desc

-- 例2:查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大排序

select * from students order by age desc,studentNo


聚合函数


-- 例1:查询学生总数 

-- select count(*) as 学生总数 from students

-- select count(name) from students


-- 注意:count(card) 不统计为null数据

-- select count(card) from students



-- 例2:查询女生的最小年龄

-- select min(age) from students where sex='女'


-- 例3:查询1班的最大年龄

-- select max(age) from students where class='1班'


-- 例4:查询北京学生的年龄总和

-- select sum(age) from students where hometown='北京'


-- 例5:查询女生的平均年龄

select avg(age) from students where sex='女'


分组

-- 例1:查询各种性别的人数

-- select sex,count(*) from students group by sex


-- 例2:查询各种年龄的人数

-- select age,count(*) from students group by age


-- 例1:查询男生总人数

-- select sex,count(*) from students group by sex having sex='男'

—select count(*) from students where sex='男'


分页

  • 已知:每页显示m条数据,求:显示第n页的数据

select * from students limit (n-1)*m,m